某些日期的DateFormatter.localizedString已中断

时间:2017-09-20 10:57:01

标签: ios swift nsdateformatter

这是我在选择器更改时所做的事情:

extension Date {
    var fromCurrentToUTC: Date {
        return addingTimeInterval(-TimeInterval(TimeZone.current.secondsFromGMT()))
    }
}    


var title = "--"

if let date = datePickerView.date?.fromCurrentToUTC {
    title = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
}

print("-----")
print(datePickerView.date!)
print(title)
print(TimeZone.current)
print(datePickerView.date!.timeIntervalSince1970)

dateTimeSegmentControl.setTitle(title, forSegmentAt: 0)

这就是它查找日期的方式:

enter image description here enter image description here enter image description here enter image description here

假设。 11月6日之前的一切都很好,一切都在11月6日之后关闭。为什么呢?

更新

我使用的每个时区的关键日期都不同。例如:

华沙(+0200)日期是10月30日 芝加哥(-0500)的日期是11月6日

订购的印刷品:

-----
2017-11-04 00:00:00 +0000
4 Nov 2017
America/New_York (current)
1509753600.0
-----
2017-11-05 00:00:00 +0000
5 Nov 2017
America/New_York (current)
1509840000.0
-----
2017-11-06 00:00:00 +0000
5 Nov 2017
America/New_York (current)
1509926400.0
-----
2017-11-07 00:00:00 +0000
6 Nov 2017
America/New_York (current)
1510012800.0

1 个答案:

答案 0 :(得分:2)

在你的功能中

group by

当前日期的GMT偏移量被减去,而不是 由GMT抵消的日期进行调整。所以你得到了 如果要调整的日期是在DST期间而当前日期不是,则反映的结果是错误的,反之亦然。

可以使用

修复
group by

代替。但是,更好的解决方案是设置时区 日期格式化程序的格式,而不是调整日期:

extension Date {
    var fromCurrentToUTC: Date {
        return addingTimeInterval(-TimeInterval(TimeZone.current.secondsFromGMT()))
    }
}