Wednesday, April 16, 2008

Don't use DateTime.Parse(), use DateTime.ParseExact() instead

It seems that very few people know that DateTime.Parse() is COM dependent, evil one. Moreover, even in Microsoft.NET, there is no assurance that such string that DateTime.Parse() accepts on your machine is acceptable under other machines. Basically DateTime.Parse() is for newbies who don't mind unpredictable behavior.


DateTime.ParseExact (datestr, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), CultureInfo.CurrentCulture);

instead of


is quite annoying because of its lengthy parameters. But first thing you should do right now is to prepare your own MyDateTime.Parse() that just returns the same result of the above. It's also true to several culture-dependent String methods (IndexOf, LastIndexOf, Compare, StartsWith, EndsWith - all of them are culture sensitive, even with InvariantCulture) to avoid unexpected matches/comparisons.


docchang said...

You are missing one parameter.

public static DateTime ParseExact(
string s,
string[] formats,
IFormatProvider provider,
DateTimeStyles style

Do you know why i am getting a FormatException of "String was not recognized as a valid DateTime"?

DateTime.ParseExact("2008-10-01 16:44:120.000", "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));

docchang said...

Got it!

DateTime.ParseExact("2008-10-01 16:44:12.000", "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));

Capital HH and 12 second not 120...