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.
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;