Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to DateTime in c#

Tags:

What is the easiest way to convert the following date created using

dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) 

into a proper DateTime object?

20090530123001 

I have tried Convert.ToDateTime(...) but got a FormatException.

like image 973
Grant Avatar asked Oct 20 '09 05:10

Grant


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I convert ToDateTime?

open System let convertToDateTime (value: string) = try let convertedDate = Convert. ToDateTime value printfn $"'{value}' converts to {convertedDate} {convertedDate.

What is DateTime parse in C#?

The DateTime. ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown. Date & time is culture specific; the methods either use the current culture or accept a specific culture.


2 Answers

Try this:

DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); 

If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact method like this:

DateTime dateTime; DateTime.TryParseExact(str, "yyyyMMddHHmmss",     CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime); 
like image 169
Andrew Hare Avatar answered Sep 27 '22 19:09

Andrew Hare


http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture) 
like image 37
eglasius Avatar answered Sep 27 '22 19:09

eglasius