0

According to Parsing Date and Time Strings (my emphasis):

The string representation of a date to be parsed must include the month and at least a day or year. The string representation of a time must include the hour and at least minutes or the AM/PM designator. However, parsing supplies default values for omitted components if possible. A missing date defaults to the current date, a missing year defaults to the current year, a missing day of the month defaults to the first day of the month, and a missing time defaults to midnight.

Unfortunately, this doesn't seem to work ideally when using other locales. For example, using nb-NO, my WPF DatePicker formats dates as 31.12.2017, and I want the string 1.2 to be parsed as February 1st of the current year. However, it's interpreted as the time 01.02.00 and today's date is used instead with the parsed time. (The parsing works as desired if I write 1/2, but I don't want to force users to use non-default separators for their locale.)

Is there any way to make use of .NET's built-in locale-aware date parsing, but force it to only parse the date, not time? (I can't use ParseExact because I need to support different locales; therefore, these questions aren't helpful.)

cmeeren
  • 3,890
  • 2
  • 20
  • 50
  • Do you know TryParseExact has an overload that takes an array of format strings? How many different locales you need to support? By the way months are M (uppercase) while minutes are m (lowercase) – Steve Jan 14 '18 at 21:16
  • An array of formatting strings is certainly not ideal. For example, what should take precedence of `MM/dd` and `dd/MM`? Both will succeed in many cases, yet based on the user's locale, only one of them is correct. – cmeeren Jan 14 '18 at 21:23
  • 'using nb-NO, my WPF DatePicker ... it's interpreted as the time 01.02.00' - The only way I can reproduce that behavior is to make a clone of `CultureInfo.GetCultureInfo("nb-NO")` and change its `DateTimeFormat.TimeSeparator` from **":"** to **"."**. Is it standard in that locale to use the same symbol for the DateSeperator and TimeSeparator? Or have you changed your region settings? – TnTinMn Jan 15 '18 at 02:27
  • I don't think I have actively changed any system settings, though I may be wrong. But yes, both `. ` and `: ` can be used as time separators in this locale. – cmeeren Jan 15 '18 at 05:33
  • The potential for the same character to be used for both the DateSeparator and TimeSeparator complicates things. The [source code](http://referencesource.microsoft.com/#mscorlib/system/globalization/datetimeparse.cs,f75289affb7e0ce3) appears to account for this possibility and interprets the string as a Date if one of the numbers entered is a four digit year. This does not help you though. A solution could be to retrieve the DateTimeFormatInfo.ShortDatePattern and split it. Then you could determine if it date or month first and prepare a culture specific array for ParseExact. – TnTinMn Jan 15 '18 at 21:24

0 Answers0