c sharp

How To Convert String to DateTime Object in C#

To represent date and time information in C#, the DateTime class is normally used. The conversion of a string containing a date, time, or both into a DateTime object may occasionally be necessary. In this article, we will discuss different ways to convert a string to a DateTime object in C#.

Converting String to DateTime Object in C#

1: Using DateTime.ParseExact

If you know the format of the input string, you can use the DateTime.ParseExact function for converting it to a DateTime object. The input string and a format string that describes its format are the two arguments taken by this function:

using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        string input = "2023-05-01 12:30:45";
        DateTime date = DateTime.ParseExact(input, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        Console.WriteLine(date);
    }
}

In this example, we pass the input string “2023-05-01 12:30:45” and the format string “yyyy-MM-dd HH:mm:ss” to the DateTime.ParseExact method. According to the format string, there should be four digits for the year, two for the month, two for the day, two for the hour in 24-hour format, two for the minute, and two for the second. The CultureInfo.InvariantCulture parameter tells the method to use the default culture for parsing.

2: Using DateTime.Parse

If you don’t know the format of the input string, you can use the DateTime.Parse function for creating a DateTime object from it. The input string is the only argument this function accepts.

using System;

class Program
{
    static void Main(string[] args)
    {
        string input = "2023-05-01 12:30:45";
        DateTime date = DateTime.Parse(input);
        Console.WriteLine(date);
    }
}

In this example, we pass the input string “2023-05-01 12:30:45” to the DateTime.Parse method. The method automatically detects the format of the input string and converts it to a DateTime object.

3: Using DateTime.TryParseExact

This method is quite idententcial to DateTime.ParseExact, but instead of throwing an exception if the input string is not in the correct format, it returns false.

using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        string input = "2023-05-01 12:30:45";
        DateTime date;
        if (DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            Console.WriteLine("DateTime: " + date.ToString());
        }
        else
        {
            Console.WriteLine("Unable to parse input string.");
        }
        Console.ReadLine();
    }
}

In this example, we pass the input string “2023-05-01 12:30:45” and the format string “yyyy-MM-dd HH:mm:ss” to the DateTime.TryParseExact method. The method tries to convert the input string to a DateTime object, and if successful, it assigns the result to the date variable and returns true. If the conversion fails, it returns false.

4: Using DateTime.TryParse

The DateTime.TryParse method is another way of converting a string into a DateTime value. When using this method, a boolean result is returned that reveals whether the conversion was successful or not. If the conversion is successful, it also sets the out parameter to the converted DateTime value. Here’s an example:

using System;

class Program
{
    static void Main(string[] args)
    {
        string dateString = "05/01/2022";
        DateTime date;
        if (DateTime.TryParse(dateString, out date))
        {
            Console.WriteLine(date);
        }
        else
        {
            Console.WriteLine("Invalid date format");
        }
    }
}

This code creates a string dateString with the date in “MM/dd/yyyy” format and then uses the DateTime.TryParse method to try and parse it into a DateTime object. If the conversion is successful, it outputs the parsed DateTime object to the console, otherwise, it prints an error message indicating the format is invalid.

5: Using DateTimeOffset.Parse

The DateTimeOffset.Parse method is used for converting a string into a DateTimeOffset value, which represents a time and date value along with an offset from UTC. This function returns a DateTimeOffset object after receiving a string as input.

Here’s an example:

using System;

class Program
{
    static void Main(string[] args)
    {
        string dateString = "05/01/2022 12:00:00 +05:00";
        DateTimeOffset date = DateTimeOffset.Parse(dateString);
        Console.WriteLine(date);
    }
}

In this code, the dateString variable holds the string representation of the date and time with an offset. To parse the string into a DateTimeOffset object, the DateTimeOffset.Parse() function is used

The DateTimeOffset struct represents a point in time and includes an offset from Coordinated Universal Time (UTC) that reflects the time zone of the local system. The Console.WriteLine() method is used to output the resulting DateTimeOffset object to the console.

6: Using DateTimeOffset.TryParse

The DateTimeOffset.TryParse method is similar to DateTime.TryParse, but it is used to convert a string to a DateTimeOffset. Whether the conversion was successful or not is indicated by the boolean value this method returns. If the conversion is successful, it also sets the out parameter to the converted DateTimeOffset value.

Here’s an example:

using System;

class Program
{
    static void Main(string[] args)
    {
        string dateString = "05/01/2022 12:00:00 +05:00";
        DateTimeOffset date;

        if (DateTimeOffset.TryParse(dateString, out date))
        {
            Console.WriteLine(date);
        }
        else
        {
            Console.WriteLine("Invalid date format");
        }
    }
}

This code uses the DateTimeOffset.TryParse method to parse the string “05/01/2022 12:00:00 +05:00” into a DateTimeOffset object named date. If the parse operation is successful, the program outputs the value of data to the console. If the parse operation fails, the program outputs the string “Invalid date format”.

Conclusion

Converting a string to a DateTime object in C# is a common task that can be accomplished in several ways. The DateTime.Parse or DateTime.TryParse methods are the most commonly used ways that can parse the string representation of a time and date into a DateTime object. It is important to keep in mind the formatting of the string and the culture settings of the application, as these can affect the outcome of the conversion process.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.