Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse this datetime string?

I can't figure it out, where did I go wrong?

I got the following datetime string, and need to parse it to datetime:

string timestr = "1/20/2014 12:05:16 AM"

And I trying to parse it like this:

DateTime.ParseExact( timestr,
                     "MM/dd/yyyy hh:mm:ss tt",
                     null);

When trying to do this it returns

"string was not recognized as a valid DateTime"

Any tip?

like image 256
Jason94 Avatar asked Jan 20 '14 08:01

Jason94


1 Answers

MM is for 01 to 12

Use M instead which is for 1 to 12.

string timestr = "1/20/2014 12:05:16 AM";
var date = DateTime.ParseExact(timestr,
                               "M/dd/yyyy hh:mm:ss tt",
                               CultureInfo.InvariantCulture);
Console.WriteLine(date);

Output will be;

1/20/2014 12:05:16 AM

Here a demonstration.

For more information, take a look at;

  • Custom Date and Time Format Strings

Also be careful about your hour formatting. hh is for 01 to 12, HH is for 00 to 23. If your hour will be 13, 14 or 15 etc.. hh format will fail.

And since you using null as a IFormatProvider in your DateTime.ParseExact method, that means it uses CurrentCulture by default. And if it's DateSeparator is not /, your method throws FormatException even your string and format matches exactly because "/" format specifier has a special meaning in custom date and time formats like; replace me current culture's or suplied culture date separator

like image 136
Soner Gönül Avatar answered Sep 28 '22 08:09

Soner Gönül