I have a problem parsing string to DateTime to US format. Although I provide the string in format of MM/dd/yyyy it keeps returning me the DateTime in format of dd/MM/yyyy and I have tried all of the below.
string[] formats = { "MM/dd/yyyy hh:mm:ss", "MM/dd/yyyy" };
DateTime dateTime;
var ex = DateTime.TryParseExact("12/29/1989", formats, provider, DateTimeStyles.None, out dateTime);
And the above will return me the dateTime as "29/12/1989";
I have also tried:
var dt = DateTime.Parse("12/29/1989", System.Globalization.CultureInfo.GetCultureInfo("en-US"));
basicly I have tried all the DateTime Parse option and will all return me non us format.
I am based in th UK and my machine's locale is en-UK.
all return me non us format
No, they return you a DateTime
value. A DateTime
value doesn't have a format. It's just a date and a time. When you want to convert that back into a string, it will use the default format for your current culture unless you say otherwise.
It's important to differentiate between the data stored in a value (a date and time) and string representations of that value.
To give a similar example, what would you expect the result of this code to be?
int x = Convert.ToInt32("FF", 16);
Console.WriteLine(x);
Would you expect "255" or "FF"? It's 255, because the default format for converting an int
to a string is decimal. It doesn't matter that the value was originally parsed from hex - that's not part of the value. Apply the exact same logic to DateTime
.
See more on this question at Stackoverflow