Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET DateTime not returning AM/PM in ToShortTimeString()

Tags:

c#

.net

datetime

I've run into a problem that's driving me crazy. In my application (ASP.NET MVC2 /.NET4), I simply running this:

DateTime.Now.ToShortTimeString()

All the examples I've seen indicate I should get something like: 12:32 PM, however I'm getting 12:32 without the AM/PM.

I launched LinqPad 4 to see if I could replicate this. Instead, it returns 12:32 PM correctly.

What the hell?

like image 418
chum of chance Avatar asked Aug 17 '10 17:08

chum of chance


3 Answers

You may also try a custom format to avoid culture specific confusions:

DateTime.Now.ToString("hh:mm tt")
like image 101
Darin Dimitrov Avatar answered Nov 19 '22 09:11

Darin Dimitrov


KBrimington looks to be correct:

The string returned by the ToShortTimeString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short time pattern is "h:mm tt"; for the de-DE culture, it is "HH:mm"; for the ja-JP culture, it is "H:mm". The specific format string on a particular computer can also be customized so that it differs from the standard short time format string.

From MSDN

like image 32
Martin Avatar answered Nov 19 '22 10:11

Martin


If you don't want to mess with the Culture for your whole thread/application, try this:

CultureInfo ci = new CultureInfo("en-US");
string formatedDate = DateTime.Now.ToString("t", ci);

You can find the list of DateTime Format strings here.

like image 3
AllenG Avatar answered Nov 19 '22 09:11

AllenG