Convert Date format from dd-mmm-yyyy (16-May-2013) to mm/dd/yyyy (09/12/2013)

StackOverflow https://stackoverflow.com/questions/16521687

  •  21-04-2022
  •  | 
  •  

Вопрос

I want to convert date format from dd-mmm-yyyy (16-May-2013) to date format mm/dd/yyyy (09/12/2013).

I am using this code. But still not able to get the correct value. the month value is becoming zero.

string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("mm/dd/yyyy");

In the above code txtVADate is the TextBox Control Which is giving date format like dd-mmm-yyyy example (16-May-2013).

Any Answers are appreciable.

Это было полезно?

Решение

The format specifier for month is MM not mm, try using MM/dd/yyyy. Also when using a custom format it's best to pass InvariantCulture to avoid any clashes with the current culture your app is running under i.e.

DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

See Custom Date and Time Format Strings.

Другие советы

Use capital M letter.

m - minute
M - month

You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter

string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

The slashes / mean: "replace me with the actual current date-separator of your culture-info".

To enforce / as separator you can use CultureInfo.InvariantCulture:

string dt = DateTime.Parse(txtVADate.Text.Trim())
    .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

MSDN:

/ The date separator defined in the current System.Globalization.DateTimeFormatInfo.DateSeparator property that is used to differentiate years, months, and days.

( you also have to use MM instead of mm since lower case is minute whereas uppercase is month )

string dt = datatime.toshortdatestring`

Here is your solution.

using System.Globalization;

 string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("mm/dd/yyyy", CultureInfo.InvariantCulture);

also can be done like this

 public string FormatPostingDate(string txtdate)
 {
     if (txtdate != null && txtdate != string.Empty)
     {
         DateTime postingDate = Convert.ToDateTime(txtdate);
         return string.Format("{0:mm/dd/yyyy}", postingDate);
     }
     return string.Empty;
 }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top