Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format

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 ?

like image 528
Itz.Irshad Avatar asked Dec 27 '22 16:12

Itz.Irshad


1 Answers

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
like image 87
Adam Houldsworth Avatar answered Jan 25 '23 22:01

Adam Houldsworth