Reputation: 45243
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.
Upvotes: 10
Views: 12639
Reputation: 1
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
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"));
Upvotes: 0
Reputation: 4675
Try the adding the invariant culture, Using the InvariantCulture Property
Console.WriteLine("Date: " + datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture));
Upvotes: 1
Reputation: 9173
Try:
datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);
Your culture might be overriding your date separator.
Upvotes: 14
Reputation: 11953
/
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.
Upvotes: 19
Reputation: 9629
This article explains how the current culture can change the output of DateTime.ToString(string). Read the section that contains this text:
This method uses formatting information derived from the current culture
This article explains how to get/set the culture so that you can test this possibility.
This article explains how you can explicitly provide DateTime.ToString with a culture to use.
Upvotes: 2