Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime format conversion to string ignores AM/PM

I am trying to convert DateTime object to string using formatting but due to some strange reason, it ignores AM/PM. It would just take the magnitude of the Hour in the object.

I am using the following format:

StartDate.ToString("yyyy-MM-dd hh:mm:ss.fff");

and

String.Format("0:yyyy-MM-dd hh:mm:ss.fff", StartDate);

I don't think that there is a difference between the two, but just wanted to give it a try. If I pass a value 4/28/2012 6:00:00 AM or 4/28/2012 6:00:00 PM, the result is the same "2012-04-27 06:00:00.000"

like image 683
Shakti Prakash Singh Avatar asked Oct 20 '25 09:10

Shakti Prakash Singh


1 Answers

You've used hh which uses the 12-hour clock. You want HH which uses the 24-hour clock.

See MSDN for more details about custom format strings.

Note that you may wish to specify the invariant culture, unless you really want the time separator to depend on the current culture:

string formatted = StartDate.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                      CultureInfo.InvariantCulture);

(Note that you shouldn't have the braces if you're passing the format string to ToString. I'll assume this was just a typo in the question.)

If you want to use the 12-hour clock, use tt in the format string to produce the AM/PM designator.

like image 116
Jon Skeet Avatar answered Oct 24 '25 05:10

Jon Skeet