Itz.Irshad
Itz.Irshad

Reputation: 1024

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 ?

Upvotes: 4

Views: 34670

Answers (4)

Radek82
Radek82

Reputation: 196

why not use ToShortDateTimeString()

Upvotes: 0

ChrisF
ChrisF

Reputation: 137168

If you string has the format dd/MM/yyyy then you have to use DateTime.ParseExact with the specified format:

DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Anything else will try an interpret the string according to the current culture's rules - which, as you have found, will fail.

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109762

Since your input string is in a fixed format, you should parse it in that format:

DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Upvotes: 2

Adam Houldsworth
Adam Houldsworth

Reputation: 64517

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

Upvotes: 7

Related Questions