In this blog post, we will learn how to convert a string to DateTime in C#.

Let's say you have a datetime string which has a date time value and now you want to perform some date calculations or checks or something else, you would need to convert this string to date in C#.

Luckily, C# provides us a few built in classes and methods that we can use to convert string to datetime.

Let's see each one of them below

 

 

 

 

Convert String To Datetime Using DateTime.ParseExact Method

In this method we convert string to datetime using the DateTime.ParseExact() method.

The DateTime class provides us with a lot of methods one of which is the .ParseExact() method which we can use and convert a datetime string into a datetime object in c#.

This method takes a few parameters, for example, the first parameter it takes is the datetime string that needs to be converted, then the format in which the datetime is stored in this string, and then the globalization culter information.

Let's see this in an example.

 

Example:

namespace consoleapp { public class Program { public static void Main() { string strDateTime = "2022-07-28 14:00:00"; DateTime convertedValue = DateTime.ParseExact(strDateTime, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine(convertedValue); } } }

 

Result:

28/07/2022 2:00:00 pm

 

In the above code example, the method tries to convert the string datetime value to a DateTime object based on the format passed.

In this case, the format matched the value that was passed, so the conversion was successful and the result was written to the console.

 

You also have the option to pass in multiple date formats in the case your string may have multiple date formats.

 

Example:

namespace consoleapp { public class Program { public static void Main() { string strDateTime = "2022-07-28 14:00:00"; DateTime convertedValue = DateTime.ParseExact(strDateTime, new[] { "dd-MM-yyyy", "yyyy-MM-dd HH:mm:ss" }, System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine(convertedValue); } } }

 

Result:

28/07/2022 2:00:00 pm

 

In the case where the method is unable to convert the string to datetime based on the provided format, an exception occurs.

 

Example:

namespace consoleapp { public class Program { public static void Main() { string strDateTime = "2022-07-28 14:00:00"; DateTime convertedValue = DateTime.ParseExact(strDateTime, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine(convertedValue); } } }

 

Result:

C# convert string to datetime - exception