5

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.

1 Answer 1

7

/ 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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Wow, never even realised that, because for me the date separator is "/". Good catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.