【问题标题】:Unexpected behavior with NSDateFormatter on iOS 9.1iOS 9.1 上 NSDateFormatter 的意外行为
【发布时间】:2015-10-23 10:09:40
【问题描述】:

我有这个代码:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm Z"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *sDate = [dateFormat stringFromDate:_datePicker];

_datePicker 来自 this 而 datePicker 是一个 UIDatePicker

_datePicker = datePicker.date;

这在 iOS 7 中肯定可以正常工作,现在我正在 9.1 中进行测试

因此,如果将手机设置设置为以 24 小时格式显示时间,则可以,但如果我将设置更改为无 24 小时格式,我就会有一种疏远的行为:

如果设置为 24h,则输出为:

但是如果我把它改成非 24h 是:

如您所见,就像是结合了它添加的 2 种格式,例如下午 1 点的 13 点到 131:00 小时或下午 6 点将是 186:00。

是否有办法始终以 24 小时格式获取时间?

提前致谢。

【问题讨论】:

  • 尝试不使用setLocale:
  • @Cy-4AH 谢谢,但是没有 setLocale 的结果是一样的:

标签: ios objective-c ios9


【解决方案1】:

您好,我已经在另一个页面中看到了这种方法,我已经将代码更改为:

NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy-MM-dd HH:mm Z"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone localTimeZone]];

NSString *sDate = [rfc3339DateFormatter stringFromDate: _datePicker];

现在工作正常,但我不确定这是正确的方法。

我希望这对将来的人有所帮助。

更新: This is where I got the code.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
相关资源
最近更新 更多