2

Work in Australia and have received message from US that DateTime is parsing string "Dec15" wrongly and returning Dec 15, 2016 instead of Dec 1, 2015. "Dec15" in snippets below are variables in real life.

var date = DateTime.Parse("Dec15", new CultureInfo("en-AU")); //returns December 1 2015

I can not replicate even after changing my PC Formats & Location to point to US.

However, I can replicate if I change the code to use a US culture.

var date = DateTime.Parse("Dec15", new CultureInfo("en-US")); //returns December 15 2016

I'm not aware the code has been a problem in the past. I would like some help understanding why the CultureInfo is being ignored/replaced with what appears to be there default Cultures over there in the US.

Appreciate any suggestions you may have.

RobCroll
  • 2,571
  • 1
  • 26
  • 36
  • 1
    I'm in Australia, and `DateTime.Parse("Dec15")` is indeed returning the 1st of December 2015, and not 15th December, so I think the fact they're in Australia is a red herring, and it's another issue at play – Rob May 17 '16 at 00:55
  • 1
    Dec15 is indeed 2016-12-01... There is no way to fix that for single app with config as far as I know (http://stackoverflow.com/questions/9104084/how-do-i-set-cultureinfo-currentculture-from-an-app-config-file) - but if you can't fix your broken date parsing you can ask your users to change region to whatever you like... – Alexei Levenkov May 17 '16 at 01:00

2 Answers2

3

Since Dec15 isn't a standard DateTime format, my guess is the parser doesn't recognise it regardless of the culture provided.

In order to parse it correctly, you can use the ParseExact method to provide a format to use:

var date = DateTime.ParseExact("Dec15", "MMMyy", CultureInfo.InvariantCulture);

That then provides you a DateTime object to further parse as you need to.

Steve
  • 9,335
  • 10
  • 49
  • 81
  • Yes a more robust solution but would require a new release. I'm hoping there is something on the client side that may fix this. – RobCroll May 17 '16 at 00:54
2

It all works fine, and as you can see the culture is not ignored, because you have to manually specify CultureInfo to get the desired wrong result.

I am 100% sure that if you will look at Thread.CurrentThread.CurrentUICulture you will see different results in the machine in Australia and US

The parsing is always using CurrentCulture. If you want want to have fixed format just use DateTime.ParseExact method.

Or you can force the Culture for application as shown here

Also you may want to look at this

Community
  • 1
  • 1
Peuczynski
  • 4,591
  • 1
  • 19
  • 33