我发现 DateFormatter date(from:)
方法无法解析几个特定的日期。对于 1981-1984 年的 4 月 1 日,方法返回 nil
。这是基金会的错误吗?我们可以做些什么来解析这些日期?
最佳答案
如果夏令时恰好开始于 午夜,就像 1981 年至 1984 年莫斯科的情况一样(参见示例 Clock Changes in Moscow, Russia (Moskva))。
这也被观察到
- Why does NSDateFormatter return nil date for these 4 time zones?和
- Why NSDateFormatter is returning null for a 19/10/2014 in a Brazilian time zone?
例如,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/