ios - 80 年代的 4 月 1 日日期在 iOS 10.0 中无法解析

标签 ios swift nsdateformatter foundation

我发现 DateFormatter date(from:) 方法无法解析几个特定的​​日期。对于 1981-1984 年的 4 月 1 日,方法返回 nil。这是基金会的错误吗?我们可以做些什么来解析这些日期?

Xcode 8.0,iOS SDK 10.0。这是一个简短的 Playground 示例的屏幕截图: a screenshot of a short playground example

最佳答案

如果夏令时恰好开始于 午夜,就像 1981 年至 1984 年莫斯科的情况一样(参见示例 Clock Changes in Moscow, Russia (Moskva))。

这也被观察到

例如,1984 年 4 月 1 日午夜,时钟向前调整一小时,这意味着日期“1984-04-01 00:00” 在那个时区不存在:

let dFmt = DateFormatter()
dFmt.dateFormat = "yyyy-MM-dd"
dFmt.timeZone = TimeZone(identifier: "Europe/Moscow")
print(dFmt.date(from: "1984-04-01")) // nil

作为解决方案,您可以让日期格式化程序“宽松”:

dFmt.isLenient = true

然后它将返回当天的第一个有效日期:

dFmt.isLenient = true
if let date = dFmt.date(from: "1984-04-01") {
    dFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    print(dFmt.string(from: date)) 
}
// 1984-04-01 01:00:00

A different solution 是由 rob mayoff 给出的,它使日期格式化程序使用 noon 而不是午夜作为 默认日期。以下是 rob 的代码从 Objective-C 到 Swift 的翻译:

let noon = DateComponents(calendar: dFmt.calendar, timeZone: dFmt.timeZone,
               year: 2001, month: 1, day: 1, hour: 12, minute: 0, second: 0)
dFmt.defaultDate = noon.date
if let date = dFmt.date(from: "1984-04-01") {
    dFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    print(dFmt.string(from: date)) 
}
// 1984-04-01 12:00:00

关于ios - 80 年代的 4 月 1 日日期在 iOS 10.0 中无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47054657/

相关文章:

iphone - 从整个应用程序目录的 zip 文件安装 iPhone 应用程序

ios - Swift 中的数据封装和安全性

php - 固定 : JSON cannot decode array from php

ios - Swift:去除 Spritekit 中不同场景的广告

ios - 如何快速将 UIImage 传递给 iOS 中的 Today Extension?

ios - Swift UIView 自定义位置

ios - 将 "2011-11-04T18:30:49Z"转换为 "MM/dd/yy hh:mm:SS a"格式

ios - 如何在 RestKit 中映射动态响应?

objective-c - NSDateFormatter dateFromString :stringDate returning nil in iOS 8. 3

ios - 只需要在iPhone中仅显示带有Date UIDatePicker的工作日