当系统设置为使用24小时格式时,如何获得12小时格式时间字符串

时间:2011-06-06 04:35:10

标签: ios datetime locale

我想得到一个像“10:00 PM”这样的时间字符串,我使用NSDateFormatterShortStyle来实现这一点。 但是,当系统设置为使用24小时格式时,我得到的是“22:00”。

此外,我想获得一个本地化的时间字符串。例如,在中文中,我希望得到“下午10:00”而不是“晚上10:00”。所以我必须使用[NSLocale currentLocale],并且不能使用en_US_POSIX语言环境。

请帮我获取本地化的12小时格式字符串。

我不仅需要小时部分,还需要上午/下午部分。此外,am / pm部分可能位于小时/分钟部分之前或小时/分钟部分之后,具体取决于地区。就像系统显示时间一样。 当系统设置为使用12小时格式时,它很简单。但是当系统使用24小时格式时,我无法获得本地化的12小时格式时间字符串。

3 个答案:

答案 0 :(得分:14)

这应该有效:

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格式。有关格式字符串的详细信息,请参阅Date Format Patterns的Unicode技术标准#35部分。

不幸的是,iOS会根据用户的24小时格式首选项设置重写格式字符串。我无法使用Cocoa的日期格式找到该设置。由于24小时格式将删除am / pm指定,解析结果字符串以转换大于12的小时将导致不明确的时间字符串。因此,我能看到的唯一剩余选项是尊重用户24小时偏好设置或使用其他本地化代码。您可以自己编写,也可以找一个开源替换。

答案 1 :(得分:0)

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())

答案 2 :(得分:-3)

NSInteger originalHour = hour;
BOOL isPm = YES;
if (hour >= 12) {
    if (hour > 12)
        hour -= 12;
}
else {
    isPm = NO;
}

if (hour == 0)
    hour = 12;
相关问题