convert a string to datetime in csharp

To convert a string to a DateTime object in C#, you can use the DateTime.Parse or DateTime.ParseExact methods.

Here's an example using DateTime.Parse:

main.cs
string dateString = "2022-01-01";
DateTime dateTime = DateTime.Parse(dateString);
82 chars
3 lines

And here's an example using DateTime.ParseExact, which allows you to specify a custom date format:

main.cs
string dateString = "01/01/2022";
string format = "MM/dd/yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
155 chars
4 lines

Make sure to include the System.Globalization namespace at the top of your file to access the CultureInfo class.

If the given string does not represent a valid DateTime value, a FormatException will be thrown. You can handle this exception using a try-catch block.

Note that the DateTime.Parse method is more lenient and can handle a wider range of date formats, while the DateTime.ParseExact method requires you to specify the exact format.

related categories

gistlibby LogSnag