Reputation: 43
I'm working with Xamarin (mainly forms) and a few days ago I discovered that issue.
When i call a webservice I look on response's header for Date field and try to parse it.
That works fine until 28th of February:
DateTime dt_OK = DateTime.Parse("Tue, 28 Feb 2017 11:07:06 GMT");
But, starting from 01 of March:
DateTime dt_KO = DateTime.Parse("Wed, 01 Mar 2017 11:07:06 GMT");
I get: "String was not recognized as a valid DateTime". But it is a valid datetime! 01 March 2017 was a wednesday...
ok, I know that exit ParseExact (which I tried and worked) but how about .Parse()?
DateTime dt_always_ok = DateTime.ParseExact(dateFromHeader, "ddd, dd MMM yyyy HH:mm:ss Z", System.Globalization.CultureInfo.InvariantCulture);
All days of march will not be recognized and parsed.. it restarts to work from April 01.
Anyone else faced that behaviour?
Upvotes: 4
Views: 1121
Reputation:
The issue seems reproducible only for Mono mcs
compiler, not for .Net
framework.
In that case, it looks like a known bug, because even (!)
DateTime dt_KO = DateTime.Parse("01 Mar 2017",CultureInfo.GetCultureInfo("it-IT"));
produces the following error
System.FormatException: Giorno della settimana non corretto. Stringa non riconosciuta come DateTime valido.
that means "String was not recognized as a valid DateTime because the day of week was incorrect", while "Mar"
is the correct "MMM"
format for the month.
It looks like they didn't consider that a month and a day could have the same abbreviation in the current Italian language.
A possible workaround for DateTime.Parse would be
DateTime dt_KO = DateTime.Parse("Wed, 01 Mar 2017 11:07:06 GMT",
CultureInfo.GetCultureInfo("en-US"));
Upvotes: 2
Reputation: 98840
I think Hans is on the right way. Looks like your "Mar" is not parsed in Parse
method as an abbreviate month name of the marzo which is March in Italian. It try to parse it as an abbreviate day name of the martedi instead which is tuesday in Italian. And since you try to parse two different abbreviate day names in your string, you get an exception.
But still, it is too weird to parse your english month and day names with an italian culture. Use a english-based culture instead like InvariantCulture
. And if you have a custom format, you might wanna choose ParseExact
or TryParseExact
methods to prevent this kind of ambiguous situations.
Upvotes: 3