Reputation: 99
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.
Upvotes: 3
Views: 52011
Reputation: 4638
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;
}
Upvotes: 0
Reputation: 460038
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 )
Upvotes: 1
Reputation: 2013
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);
Upvotes: 2
Reputation: 82096
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.
Upvotes: 11