DateTime.ParseExact problem with Thai / Buddhist Era Time
Asked Answered
H

1

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

Hughhughes answered 29/7, 2011 at 4:4 Comment(4)
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?Genic
Indeed are you specifying a list of formats ?Defant
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.Hughhughes
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.Ethanol
C
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.

Copeland answered 29/7, 2011 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.