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.

Yes,

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

instead of

DateTime.Parse(datestr);

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.

http://msdn.microsoft.com/msdnmag/issues/05/03/CultureInfo/default.aspx?side=true#a

2 comments:

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...