NSDateFormatter在12小时模式下

Ser*_*gey 25 datetime objective-c nsdate nsdateformatter ios

我有以下代码.

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
Run Code Online (Sandbox Code Playgroud)

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

Oma*_*ith 54

在你的NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" HH看台24小时,hh站立12小时

  • @Sergey然后使用**hh**而不是**HH** (6认同)
  • 这不是真的.如果用户关闭24小时并使用HH,则仍为12小时格式. (6认同)

ale*_*oot 34

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

NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
df.locale = twelveHourLocale;
Run Code Online (Sandbox Code Playgroud)

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

NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
Run Code Online (Sandbox Code Playgroud)


Lui*_*rbe 6

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]];
Run Code Online (Sandbox Code Playgroud)

对于24小时模式到12小时模式,只需相反