CultureInfo & DateTimeInfo: How to check if is 24 hour time?

余生长醉 提交于 2019-11-29 03:55:42

I don't think there is a better way to obtain that information. The time pattern for a culture could contain anything (a user could even create a custom culture where the ShortTimePattern is "\hello" and then DateTime.ToString() would return "hello" for any time). In that case how could the framework determine if that CultureInfo is in 24-hour or 12-hour format?

So a "normal" DateTimeFormatInfo.ShortTimePattern will necessarily contain either a 'h' or a 'H', otherwise the hour will not be displayed. I think you can follow your initial idea and check for that. You can also check that the 'h' or 'H' is not escaped with a \ like in my "\hello" example because that would not represent the hour :)

The most robust way is to check if DateTimeFormatInfo.AMDesignator is an empty string.

if (DateTimeFormatInfo.CurrentInfo.AMDesignator == "")
  //24hour format
else
  //12hour format

Checking for 'H'/'h' seems more robust than checking for the AM/PM Designator. A good example is en-gb: The time format string is HH:mm and the AM/PM designators are set to AM/PM Windows will display the time in 24h format! This seems to be an inconsistent definition but checking for 'H' fixed my bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!