Bappy
Bappy

Reputation: 109

changing date time format

Hi I am trying to change my input date time format to a specific format like "yyyy/MM/dd" But it changes to "yyyy-MM-dd" I don't know why. Here is my code.

string format = "yyyy/MM/dd";
DateTime dt = Convert.ToDateTime(dateTimePicker1.Text);
string idate = dt.ToString("yyyy/MM/dd");

Upvotes: 2

Views: 181

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460158

You have to specify CultureInfo.InvariantCulture:

string idate = dt.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

Read: The "/" Custom Format Specifier:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture....

So / is replaced by your current culture's date-separator otherwise.

Upvotes: 4

Habib
Habib

Reputation: 223277

Just supply CultureInfo.InvariantCulture

string idate = dt.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

It is considering your DateTime separator based on your current culture. Which in your case seems to be -.

Upvotes: 5

Related Questions