文化信息与 DateTimeInfo:如何检查是否是24小时时间?
我正在修改一个全球化的 Web 应用程序,该应用程序为每个登录用户使用存储的 CultureInfo。
客户希望时间数据输入能够本地化。 显示不是问题,因为格式已经可用。 不过,我需要检测当前的文化信息是否为 24 小时时间或上午/下午,以便我可以显示正确的输入框(而不仅仅是文本字段)。
我最初的想法是检查 CultureInfo 的 DateTimeInfo 属性,看看 ShortTimePattern 是否包含大写 H 或小写 h,但这对我来说感觉不够强大。
有没有更好的办法? 我已经阅读了两者的类属性,但除非我遗漏了某些内容,否则我看不到任何现有的方法或属性。
I'm modifying a globalized web application which uses stored CultureInfo for each logged in user.
The client would like time data entry to be localized. Displaying is not a problem as the formatting is already available. However I need to detect if the current cultureinfo is for 24 hour time or am/pm so I can display the correct input boxes (not just a textfield).
My initial idea was to check the DateTimeInfo property of CultureInfo and see if the ShortTimePattern contained a capital H or a lower case h but this didn't feel robust enough for me.
Is there a better way? I've read the class properties of both but unless I'm missing something, I can't see any existing methods or properties.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有更好的方法来获取该信息。 区域性的时间模式可以包含任何内容(用户甚至可以创建自定义区域性,其中 ShortTimePattern 为“\hello”,然后
DateTime.ToString()
将在任何时间返回“hello”)。 在这种情况下,框架如何确定 CultureInfo 是 24 小时还是 12 小时格式?因此,“正常”
DateTimeFormatInfo.ShortTimePattern
必须包含“h”或“H”,否则将不会显示小时。 我认为您可以按照您最初的想法进行检查。 您还可以检查“h”或“H”是否没有像我的“\hello”示例中那样用 \ 转义,因为它不代表小时:)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 :)检查“H”/“h”似乎比检查 AM/PM 指示符更可靠。
en-gb 就是一个很好的例子:
时间格式字符串为 HH:mm,AM/PM 指示符设置为 AM/PM
Windows 将以 24 小时格式显示时间!
这似乎是一个不一致的定义,但检查“H”修复了我的错误。
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.
最可靠的方法是检查 DateTimeFormatInfo.AMDesignator 是一个空字符串。
The most robust way is to check if DateTimeFormatInfo.AMDesignator is an empty string.