![](/img/trans.png)
[英]How to check if the current string is in 24 hour format time or 12 hour format time in swift3?
[英]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 小时格式时间字符串。
我不仅需要小时部分,还需要上午/下午部分。 此外,上午/下午部分可能位于小时/分钟部分之前或小时/分钟部分之后,具体取决于区域设置。 就像系统显示时间一样。 当系统设置为使用 12 小时格式时,这很简单。 但是当系统使用 24 小时格式时,我无法获取本地化的 12 小时格式时间字符串。
那么这应该工作:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"hh:mm a" options:0 locale:[NSLocale currentLocale]]];
NSString *theTime = [dateFormatter stringFromDate:[NSDate date]];
这应该会为您提供一个日期格式化程序,它将以 12 小时格式给出日期。 小写的 hh 表示小时 1-12 格式。 有关格式字符串的详细信息,请参阅日期格式模式的 Unicode 技术标准 #35 部分。
不幸的是 iOS 将根据用户的 24 小时格式首选项设置重写格式字符串。 我无法使用 Cocoa 的日期格式绕过该设置。 由于 24 小时格式将删除 am/pm 指定,解析结果字符串以转换大于 12 的小时数将导致时间字符串不明确。 因此,我能看到的唯一剩余选项是尊重用户 24 小时偏好设置或使用其他本地化代码。 你可以自己写,或者找一个开源的替代品。
Swift 3.0
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "hh:mm a", options: 0, locale: NSLocale.current)
var theTime: String = dateFormatter.string(from: Date())
NSInteger originalHour = hour;
BOOL isPm = YES;
if (hour >= 12) {
if (hour > 12)
hour -= 12;
}
else {
isPm = NO;
}
if (hour == 0)
hour = 12;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.