A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.
I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:
Input: "04/10/2012" Output: 2012-04-10
Code:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
How I can fix that ?
It looks to me like you need to parse it with a fixed format, I think you are currently parsing it with a format other than "dd/MM/yyyy" and because the date is ambiguous (as in, month and day can be interchanged without causing invalid dates) the format is simply switching the month and day value. When you then go to output it, it looks reversed.
Use DateTime.ParseExact
to force the parsing format and then use the built-in current culture sensitive string output methods on DateTime
to get a formatted string:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With