Reputation: 1916
string dateString = "12/9/2014 10:09:28 AM";
DateTime dateTime;
if (DateTime.TryParse(dateString, CultureInfo.GetCultureInfo("en-GB"),
DateTimeStyles.AssumeUniversal, out dateTime))
{
Console.WriteLine(dateTime); //"9/12/2014 10:09:28 PM";
}
When I do the same with "en-US" they swap to the "12/9/2014 10:09:28 PM"
Why did they swap day and month?
How they now where are day and where are a month?
Upvotes: 4
Views: 86
Reputation: 396
That's simply because each culture can have its own date and time notation. The interpretation depends on your culture, just like pants mean trousers in the US but mean underwear in the UK!
In the en-GB culture dates are written in the "day month year" order and in the en-US culture dates are written in the "month day, year" order.
To avoid surprises or being dependant on the machine's culture you can use CultureInfo.InvariantCulture
or use ParseExact
.
If you do not specify a culture, like you have in your TryParse
call, it defaults to the current thread's culture, which is the machine's culture. You probably have en-US
as your culture, you can check this in Control Panel > Region and Language.
Upvotes: 5
Reputation: 31404
They swap the month and date because in the US the date format is Month/Day/Year and in Great Britain (and most of the rest of the world) the data format is Day/Month/Year. So in the US "12/9/2014" is December, 9th 2014 and in GB it is September 12th, 2014.
That information is determined by CultureInfo.DateTimeFormat
.
This means that you cannot interpret a date string without knowing what culture it comes from.
Upvotes: 7