开发者

C# DateTime formatting: How to display only the full hours, eg. 2 PM? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture

I'm having some problems formatting my DateTime-ob开发者_StackOverflow中文版jects so that only the full hours are shown. For example if I have the following DateTime:

? StartTime
{7/25/2011 8:00:00 AM}

I would like to print this out as "8 AM". The formatting should also follow the rules of the current culture, so in other countries the above example could be printed as "8". And 4 PM would be shown as 16.

I haven't found any built-in formatters to do this so I thought about writing some static method to handle the problem. I need to get the hours in the correct format (single or two digits) and the string designator for the given hour. String designator is easy with the ToString("tt") and this correctly returns empty if the current culture uses the 24h format. So I'm half way there.

But then I'm stuck because the CultureInfo's DateTimeFormatInfo doesn't seem to tell me if I should show the hours with one or two digits (h vs H).

Any ideas?


I think you can use the hh format combined with tt.

DateTime x = new DateTime(2011,10,10,08,00)
Console.WriteLine(x.ToString("h tt")); // Output: '8 AM'

x = new DateTime(2011,10,10,16,08,00)
Console.WriteLine(x.ToString("h tt")); // Output: '4 PM'

Have a look at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#Y16327

UPDATE:

I think Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture gives you the answer how to display the hours according to the CultureInfo (either 12 or 24 hours).


(Adding another answer as my mobile connection is failing for edit.)

Okay, if you already know whether the culture uses an am/pm designator or not, that also tells you whether to use h or H - you don't want to use h if there's no designator, as that's ambiguous ("8" could mean "8 am" or "8 pm").

So either use h tt or %H depending on the result of determining whether there's an am/pm designator or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜