系统设置为24小时格式时,如何获取12小时格式的时间字符串 [英] How to get 12 hour format time string when system is set to use 24 hour format
问题描述
我想得到一个10:00 PM的时间字符串,我使用NSDateFormatterShortStyle来实现这一点。
然而,当系统设置为使用24小时格式时,我得到的是22:00。
此外,我想要获得一个本地化时间字符串。例如,中文,我想要下午10:00而不是10:00 PM。所以我必须使用[NSLocale currentLocale],并且不能使用en_US_POSIX语言环境。
请帮助我获得本地化的12小时格式的时间字符串。 / p>
我不仅需要小时部分,还有am / pm部分。此外,am / pm部分可能位于小时/分钟之前或之后的时间/分钟部分,具体取决于语言环境。就像系统显示时间一样。
当系统设置为使用12小时格式时,它只是简单。但是当系统使用24小时格式时,我无法获得本地化的12小时格式时间字符串。
这应该工作:
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@hh:mm aoptions:0 locale:[NSLocale currentLocale]]];
NSString * theTime = [dateFormatter stringFromDate:[NSDate date]];
这应该会提供一个日期格式化程序,以12小时格式给出日期。小写字母hh表示小时1-12格式。有关格式字符串的详细信息,请参阅日期格式模式的Unicode技术标准#35部分。 / p>
不幸的是,iOS会根据用户的24小时格式首选项设置重写格式字符串。我可以找到没有办法使用Cocoa的日期格式设置。由于24小时格式将丢弃am / pm指定,因此解析生成的字符串以转换大于12的小时将导致模糊的时间字符串。因此,我唯一可以看到的选项是尊重用户24小时偏好设置或使用其他本地化代码。您可以自己编写,或者可以找到一个开源的替代品。
I want to get a time string like "10:00 PM", and I use the NSDateFormatterShortStyle to achieve this. However when the system is set to use 24-hour format, what I got is "22:00".
Besides, I want to get a localized time string. For example, in Chinese, I want to get "下午10:00" instead of "10:00 PM". So I have to use the [NSLocale currentLocale], and can't use the en_US_POSIX locale.
Please help me to get a localized 12-hour format time string.
I need not only the hour part, and also the am/pm part. Besides, am/pm part may locate before the hour/minute part or after the hour/minute part depending on locale. Just like the system display time. When system is set to use 12-hour format, it's just simple. But when the system is using 24-hour format, I just can't get the localized 12-hour format time string.
Well this should work:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"hh:mm a" options:0 locale:[NSLocale currentLocale]]];
NSString *theTime = [dateFormatter stringFromDate:[NSDate date]];
This should get you a date formatter that will give the date in 12 hour format. The lower case hh indicates hours 1-12 format. See the Unicode Technical Standard #35 section of Date Format Patterns for details on the format string.
Unfortunately iOS will rewrite the format string based on the user's 24-hour format preference setting. I can find no way around that setting using Cocoa's date formatting. Since the 24-hour format will drop the am/pm designation, parsing the resulting string to convert hours greater than 12 will result in ambiguous time strings. Therefore the only remaining options I can see is honoring the users 24-hour preference setting or using other localization code. You can write your own, or maybe find an open source replacement.
这篇关于系统设置为24小时格式时,如何获取12小时格式的时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!