Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom DateTime format string not working as expected

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.

like image 563
Jesse Webb Avatar asked Oct 11 '12 22:10

Jesse Webb


2 Answers

/ 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.

like image 182
MiMo Avatar answered Oct 28 '22 10:10

MiMo


Try:

datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);

Your culture might be overriding your date separator.

like image 32
lahsrah Avatar answered Oct 28 '22 09:10

lahsrah