2
如何从NSDate获取本地小时数,分别为12小时/ 24小时,由设备上的用户设置? 考虑日期为“2015年6月3日下午3:00” 如果12小时格式被设置,那么它应该显示下午3点(不含分钟一部分) 如果组24小时的格式,那么它应该显示15(不含分钟一部分)iOS:从NSDate获取本地化小时
我尝试过在所有语言环境中都没有成功。例如,它适用于de_DE & fr_FR,但对于en_US,它始终返回3,而不是AM/PM。
NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSString *localeFormatString = [NSDateFormatter dateFormatFromTemplate:@"HH" options:0 locale:dateFormatter.locale];
dateFormatter.dateFormat = localeFormatString;
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
NSString * hour = [dateFormatter stringFromDate:date];
NSLog(@"%@",hour);
P.S. 如果使用以下代码得到时间字符串(小时数&分钟),它可以很好地适用于语言环境以及12/24小时时间格式。但是我只想得到几个小时,而这在12/24小时时间格式中不能实现。
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.timeStyle = NSDateFormatterShortStyle;
timeFormatter.dateFormat = NSDateFormatterNoStyle;
timeFormatter.AMSymbol = @"a";
timeFormatter.PMSymbol = @"p";
timeFormatter.timeZone = timeZone;
return [timeFormatter stringFromDate:date];
谢谢。不过,我不需要整个日期字符串只有几个小时,将尝试与您的代码格式“hh a”。 –
这不是特定的12/24小时格式,它总是在上午/下午返回小时。但是如果时间格式为24小时,它不应该返回上午/下午。 –
使用以下代码转换am/pm dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@“en_US_POSIX”]; – Mahesh