Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting DateTime to string

The following code:

DateTime dt = new DateTime(2013, 9, 13, 14, 34, 0);
string s = dt.ToString("MM/dd/yyyy");

textBox1.AppendText(DateTime.Now + "\n");
textBox1.AppendText(s + "\n");
textBox1.AppendText(dt.ToString() + "\n");

produces the following output in the textbox:

13.09.2013 1441.28
09.13.2013
13.09.2013 1434.00

From the first line of the output, it is clear that in the regional setting of my PC, date/time is formatted as date.month.year HHmm.ss.

The second line of the output is confusing to me. Though I specified MM/dd/yyyy format for the variable s, the DateTime object is formatted as MM.dd.yyyy. Why?

This is a C# WPF program on .NET Framework 4.

like image 365
Donotalo Avatar asked Sep 13 '13 08:09

Donotalo


1 Answers

/ is the placeholder for your current culture's date separator. If you want to enforce it as separator you have to specify CultureInfo.InvariantCulture:

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

See: The "/" Custom Format Specifier

The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.


The same is true if you want to parse a string to DateTime.

Following throws a FormatException if your current culture's actual date-separator is not /:

DateTime.ParseExact("09/13/2013", "MM/dd/yyyy", null);  

works always:

DateTime.ParseExact("09/13/2013", "MM/dd/yyyy", CultureInfo.InvariantCulture);
like image 71
Tim Schmelter Avatar answered Sep 19 '22 12:09

Tim Schmelter