This blog has moved to Medium

Subscribe via email


Globalizing DateTime.TryParse()

DateTime.TryParse() is the sane method in .NET to parse date strings (don’t use Date.Parse() – you want to handle bad user input correctly, and throwing exceptions usually isn’t the correct way, especially if all you want is to just skip the bad date field). Well, I’ve just discovered yesterday that the dates it returns are in the local computer time. If you try to parse “31/12/08 23:59:59” and you happen to be in GMT+2, the time you’ll get will be 2 hours off.

To solve, simply run ToUniversal() on the resulting DateTime. I use:

bool TryParseUniversal(string dateString, out DateTime date)
{
  if (!DateTime.TryParse(dateString, out date))
    return false;
 
  date = date.ToUniversal();
  return true;
}