11

I need to convert "28/08/2012" to MM/dd/YYYY format that means "08/28/2012".
How can I do that?

I am using below code , but it threw exception to me.

DateTime.ParseExact("28/08/2012", "ddMMyyyy",  CultureInfo.InvariantCulture)
Himanshu Jansari
  • 28,446
  • 26
  • 101
  • 128
Lajja Thaker
  • 1,909
  • 8
  • 28
  • 52

2 Answers2

25

but it threw exception to me

Problem:

Your date contains / seperator ("28/08/2012") and you are not giving that in your date string format ("ddMMyyyy").

Solution:

It should be "dd/MM/yyyy".

This way

DateTime.ParseExact("28/08/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture)
                        .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

After doing that we will receive a DateTime object with your populated dates which is transferred to string using .ToString() with desired date format "MM/dd/yyyy" and optional culture info CultureInfo.InvariantCulture.

Nikhil Agrawal
  • 42,396
  • 22
  • 107
  • 187
1

Since your original date is in en-GB culture, you can create a CultureInfo object and parse your DateTime naturally.

string date = "28/08/2012";
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
Convert.ToDateTime(date,ci.DateTimeFormat).ToString("d");//short date pattern

(OR)

DateTime.Parse(date,ci.DateTimeFormat).ToString("d");
Antony Thomas
  • 3,266
  • 1
  • 30
  • 37