-2

I am trying to convert string dd-mm-yyyy to MM/dd/yyyy. I have tried different ways but nothing worked. My current logic is:

 string convertDate = DateTime.ParseExact(date, "dd-mm-yyyy", CultureInfo.InvariantCulture)
                      .ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);

It is not converting the date as expected. It puts month on place of day and day on place of month and if day greater than 12 than it sets month to 01.

John Adam
  • 220
  • 2
  • 14

3 Answers3

4

You should consistantly be using MM to represent "Month" in both your parse, and your format specifiers. (mm means "Minute"!)

 string convertDate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture)
                  .ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);

Live example: http://rextester.com/KNA28139

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You should modify your ParseExact pattern from dd-mm-yyyy to dd-MM-yyyy because mm means minutes with 0 padding. Then your code will work pretty well for your aim. You can try the code below.

string date = "18-05-2017";
string convertDate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);
Console.WriteLine(convertDate);
Cihan Uygun
  • 2,128
  • 1
  • 16
  • 26
-1

If you want to format the DateTime, what I'd probably do is simply use a .ToString() method on the DateTime object and afterwards change the culture on a new line, like such:

Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

var date = DateTime.Now.ToString("MM/dd/yyyy");
Xariez
  • 759
  • 7
  • 24
  • I think you missed the actual mistake in the OP's question. It wasnt the output that was wrong, it was the input. – Jamiec May 18 '17 at 13:34
  • Ah, in that case this solution won't do much then. Thanks for letting me know! @Jamiec – Xariez May 18 '17 at 13:35