Parsing a DateTime containing milliseconds fails for certain cultures. Why?
Asked Answered
S

1

7

I'm trying to parse a string containing milliseconds like this:

string s = "11.05.2010 15:03:08.7718687"; // culture: de-CH
DateTime d = DateTime.Parse(s); // works

However, for example under the de-DE locale, the decimal separator is a comma (not a dot). So the example becomes:

string s = "11.05.2010 15:03:08,7718687"; // culture: de-DE (note the comma)
DateTime d = DateTime.Parse(s); // throws a FormatException

It is weird to me that DateTime.Parse(s) should throw a FormatException now as it is supposed to use the CultureInfo.CurrentCulture to do the parsing. Even passing the CurrentCulture as an argument explicitly does not help neither. Does anybody have an idea why this does not work? Doesn't parsing take the NumberFormatInfo.NumberDecimalSeparator into account?

Sweatband answered 11/5, 2010 at 13:48 Comment(1)
In the days before sub-second time formatting was standardized (ISO 8601:2004 did it), then it didn't matter what the separator was. So, the standards generally don't cover what should be used as the decimal point for sub-second times. It isn't clear that numeric format information is correct, but there isn't necessarily a better alternative. We've been wrestling with the issue recently (in an entirely different context - not Windows platforms), and not yet come up with a good system for it. Plus backwards (in)compatibility is giving us a few headaches.Tanatanach
V
4

DateTimeFormatInfo applies to formatting/parsing dates, not NumberFormatInfo. DateTimeFormatInfo does not define a "seconds/milliseconds" separator that can be overloaded by different cultures.

None of the Standard Date and Time format strings display the milliseconds, except for roundtrip, which doesn't appear to be culture sensitive anyway. So you shouldn't happen upon a string in that format, unless your own code is generating it. If you know your code is going to generate dates in that format, you can provide a custom format string that uses the comma as the separator between seconds and milliseconds.

Vatic answered 11/5, 2010 at 14:8 Comment(1)
Indeed, reflecting the DateTime.Parse method eventually leads to this code fragment: char ch2 = str.Value[str.Index]; if (ch2 == '.') { ParseFraction(ref str, out raw.fraction); } Which lets me believe that '.' is always the right choice and that there are no official standards around for a decimal separator for milliseconds (at least not in the .NET world)...Sweatband

© 2022 - 2024 — McMap. All rights reserved.