Maarten Ureel
Maarten Ureel

Reputation: 475

DateTime.TryParseExact returning false for localized date

I am trying to parse a Dutch date from some logfiles but C# DateTime.TryParseExact is always returning false:

DateTime.TryParseExact("mei 21, 2015 12:25:35:719 AM", "MMM dd, yyyy hh:mm:ss:fff tt", new CultureInfo("nl-BE"), DateTimeStyles.None, out date)

Returns false; however I don't see what could be wrong with my date format?

However this returns true:

DateTime.TryParseExact("May 21, 2015 12:25:35:719 AM", "MMM dd, yyyy hh:mm:ss:fff tt", new CultureInfo("en-US"), DateTimeStyles.None, out date) true    bool

So that would mean "nl-BE" does not know the word "mei", while en-US has no problem with "May". What can I do to overcome this?

Upvotes: 1

Views: 584

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283733

I found the same thing as Jon using a different method. It does round-trip, but no AM/PM designator is used in either direction -- the tt format field neither generates nor matches anything at all.

Test code:

DateTime date;
string fmt = "MMM dd, yyyy hh:mm:ss:fff tt";
Console.WriteLine(DateTime.TryParseExact("May 21, 2015 12:25:35:719 AM", fmt, new CultureInfo("en-US"), DateTimeStyles.None, out date));
CultureInfo dutch = new CultureInfo("nl-BE");
String s = date.ToString(fmt, dutch);
Console.WriteLine(s);
Console.WriteLine(DateTime.TryParseExact(s, fmt, dutch, DateTimeStyles.None, out date));

Output:

True
mei 21, 2015 12:25:35:719 
True

In fact, the tt field is solidly broken in that locale, because it does change from a 24-hour to 12-hour clock, but with no differentiation whatsoever between the first and second half of the day.

Online compiler: http://rextester.com/UYR26148

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502006

It looks like that culture doesn't use an AM designator:

var culture = new CultureInfo("nl-BE");
Console.WriteLine("x{0}x", culture.DateTimeFormat.AMDesignator);

That prints xx, suggesting that the AM designator is empty.

You can modify this though:

var culture = (CultureInfo) new CultureInfo("nl-BE");
culture.DateTimeFormat.AMDesignator = "AM";
culture.DateTimeFormat.PMDesignator = "PM";
DateTime date;
var result = DateTime.TryParseExact("mei 21, 2015 12:25:35:719 AM",
                       "MMM dd, yyyy hh:mm:ss:fff tt",
                       culture,
                       DateTimeStyles.None, out date);
...

Upvotes: 3

Related Questions