Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse string to dateTime in c#?

Tags:

date

c#

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?

like image 973
Anatoly Avatar asked Dec 14 '22 12:12

Anatoly


1 Answers

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.

like image 91
shf301 Avatar answered Dec 28 '22 05:12

shf301