How to get a 12-hour time format when the system is configured to use the 24-hour format

I want to get a temporary string like "10:00 PM", and for this I use NSDateFormatterShortStyle. However, when the system is configured to use the 24-hour format, I got "22:00".

In addition, I want to get a localized time string. For example, in Chinese, I want to get "δΈ‹εˆ 10:00" instead of "10:00 PM". Therefore, I must use [NSLocale currentLocale] and cannot use the en_US_POSIX locale.

Please help me get a localized 12-hour time format string.

I need not only the hour part, but also the am / pm part. In addition, the am / pm part may be located before the hour / minute part or after the hour / minute part, depending on the locale. In the same way as the system display time. When the system is configured to use the 12-hour format, it’s easy. But when the system uses a 24-hour format, I just can't get a localized 12-hour time format string.

+3
source share
3 answers

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 give you a date format that will give a date in 12 hour format. The lower case hh indicates the clock format 1-12. For more information on format strings, see "Technical Standard Unicode No. 35 of the " Date Format " section .

, iOS 24 . Cocoa. 24- am/pm, 12 . , , 24- . .

+13

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())
0
NSInteger originalHour = hour;
BOOL isPm = YES;
if (hour >= 12) {
    if (hour > 12)
        hour -= 12;
}
else {
    isPm = NO;
}

if (hour == 0)
    hour = 12;
-2

All Articles