NSDateFormatter采用12小时模式

我有以下代码。

NSDateFormatter *df = ...; [df setTimeZone:[NSTimeZone defaultTimeZone]]; [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"]; NSDate * date = [df dateFromString:date_string]; //here is the problem 

在24小时模式下一切都很好。 在设备上设置12小时模式时,stringFromDate返回null。 date_string的格式也始终相同,日期格式也一样。 为什么会这样?

尝试以这种方式设置区域设置:

 NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; df.locale = twelveHourLocale; 

要强制改为24小时,您可以使用:

 NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; 

在你的NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" HH代表24小时, hh代表12小时

12小时模式到24小时模式:

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm a"]; NSDate *amPmDate = [formatter dateFromString:amPmHourString]; [formatter setDateFormat:@"HH:mm"]; NSString *24HourString = [formatter stringFromDate:amPmDate]]; 

对于24小时模式到12小时模式,只需做相反的操作

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; [dateFormat setLocale:locale];