7

After client downloads a file from our server with our app, the app does a ParseExact on a date string which comes down from the server in the form: yyyy/mm/dd HH:mm:ss.

After alot of confusion, I noticed in some logs that the date on the clients system was 19/7/2554. As is turns out this is a valid time as in Thailand, Windows defaults to the Buddhist era time system, where it is the year 2554.

My parse exact is done with an invariant culture, which I suspect may be the problem, but I thought that the culture referred to the format which you were trying to parse?

The exception message I get is: String was not recognized as a valid DateTime because the day of week was incorrect

John Kar.
  • 605
  • 1
  • 7
  • 10
James R
  • 651
  • 1
  • 12
  • 21
  • Your format doesn't seem to include day of the week at all. Can you give an example of the string you're trying to parse and the code that's doing the parsing? – Adam Lear Jul 29 '11 at 04:24
  • Indeed are you specifying a list of formats ? – V4Vendetta Jul 29 '11 at 04:31
  • Ah my bad guys, I screwed up. Turns out there was another piece of code running which I didn't even know about. It was pretty hard to debug with only an exception message from a log file. Turns out it was a DateTime.Parse error, not a parseexact. I was able to replicate the problem by changing my PC's region to Thailand and see exactly where it was dying. – James R Jul 31 '11 at 11:25
  • I believe Invariant Culture should not cause you problems, and this is I think the correct way of parsing, so that your code is working regardless of the specific formats of the different cultures. If InvariantCulture does not work for you, I'd be thankful to learn more about your issue, since I myself am using Invariant Culture for my projects. – Ivaylo Slavov Dec 07 '11 at 15:39

1 Answers1

1

The CultureInfo also contains calendar information. If the TryParseExact method has access to the correct calendar information then it will be able to parse the date correctly.

http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.calendar.aspx

If you replace the InvariantCulture CultureInfo with the Thai CultureInfo then the default calendar for that culture will be used.

Alternatively, you could use an overload of the TryParse method that does not require a CultureInfo. The culture that is used in this case will be dependant on the user's regional settings in Windows.

Scott Munro
  • 13,369
  • 3
  • 74
  • 80