I have a custom DateTime
format string: "M/d/yyyy h:m:ss tt"
.
For example, with the date 'September 18th, 2012 @ noon', I expect the output of this to be something like "9/18/2012 12:0:00 PM"
.
The time seems to be formatting properly, but the date portion is getting messed up. I am seeing the dates formatted as "MM-dd-yyyy"
and I can't figure out why.
Here is some sample code to reproduce the problem:
var datetime = DateTime.Now;
Console.WriteLine("Date: " + datetime.ToString("MMMM d, yyyy")); // Date: October 11, 2012 --> correct
Console.WriteLine("Date: " + datetime.ToString("M/d/yyyy h:m:ss tt")); // Date: 10-11-2012 4:34:17 PM --> wrong
Here is the MSDN doc for custom DateTime format strings.
Any ideas on what am I doing wrong? How can I achieve my desired result?
Edit:
The thing that is incorrect in the last line of sample code is that there is hyphens instead of slashes and I don't know why.
Also, my computer's language is set to English (Canada). But neither my "short" nor "long" date format look like M-d-yyyy
so I have no idea where that is coming from.
/
is the date separator, that is culture-dependant - in your current culture it is defined as -
. If you want always a /
use:
Console.WriteLine("Date: " + datetime.ToString("M\"/\"d\"/\"yyyy h:m:ss tt"));
or
Console.WriteLine("Date: " + datetime.ToString("M'/'d'/'yyyy h:m:ss tt"));
i.e. put the parts that you want to be output 'as is' inside quotes.
Try:
datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);
Your culture might be overriding your date separator.
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