0

My machine is configured with European date format: dd/MM/yyyy

When running any of the following lines:

DateTime.Parse("11/15/2017 12:00:00 AM");
DateTime.Parse("11/15/2017 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"));
DateTime.Parse("11/15/2017 12:00:00 AM", CultureInfo.CreateSpecificCulture("fr-FR"));
DateTime.Parse("11/15/2017 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-GB"));

I'm getting

System.FormatException: String was not recognized as a valid DateTime.

Why doesn't any culture info allow me to parse this date? I know in which culture the string was originally created (using DateTime.ToString()), but that's it, so I don't want to use ParseExact, unless there is some API to get the default format string per culture.

Mugen
  • 8,301
  • 10
  • 62
  • 140

2 Answers2

1

This does work on a machine where the date pattern was left to default:

var culture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine(culture.DateTimeFormat.ShortDatePattern);
Console.WriteLine(culture.DateTimeFormat.ShortTimePattern);
var date = DateTime.Parse("11/15/2017 12:00:00 AM", culture);
Console.WriteLine(date);

The default date pattern for en-US is "M/d/yyyy" and the time pattern is "h:mm tt".

This holds true unless you modify your system settings for the current culture, and that culture is en-US.

If you want to bypass customized settings, create a new CultureInfo("en-US", false).

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

As you mention you are configured with dd/MM/yyyy

thus "11/15/2017 12:00:00 AM" is invalid. It should be:

"15/11/2017 12:00:00 AM"`

As a good practice, better use ParseExact, where you can specify the format of input string. Try:

DateTime.ParseExact("11/15/2017 12:00:00 AM", "MM/dd/yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-US"));
apomene
  • 14,282
  • 9
  • 46
  • 72
  • Well isn't this why culture info is there to begin with? – Mugen May 15 '18 at 12:37
  • This is the format of my machine, if I change my machine to use `MM/dd/yyyy` no exception is thrown, why machine cannot be overriden? – Mugen May 15 '18 at 12:39