Search code examples
c#date-conversion

How to convert dd-mm-yyyy Format to MM/dd/yyyy in C#?


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.


Solution

  • 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