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.
/
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With