简体   繁体   English

使用 timeIntervalSince1970 时日期不相等

[英]Dates are not equal while using timeIntervalSince1970

I've just run the code below several times and see that sometimes date1 and date2 are equal but sometimes are not.我刚刚运行了几次下面的代码,发现有时 date1 和 date2 相等,但有时不相等。

    let date1 = Date()
    let date2 = Date(timeIntervalSince1970: date1.timeIntervalSince1970)

    print(date1)
    print(date2)
    print(date1.timeIntervalSince1970)
    print(date2.timeIntervalSince1970)
    print(date1 == date2)

So sometimes I get:所以有时我会得到:

2019-03-22 05:52:30 +0000
2019-03-22 05:52:30 +0000

1553233950.498001
1553233950.498001

false

These dates look the same but comparison tells me they are different.这些日期看起来相同,但比较告诉我它们是不同的。 The problem is that the date2 is slightly different from the date1.问题是 date2 与 date1 略有不同。 To prove it I can write:为了证明这一点,我可以写:

print(date1.timeIntervalSince(date2))

and get:并得到:

-1.1920928955078125e-07 -1.1920928955078125e-07

So it there any way to translate date1 to number and then back to date2 which is equal to date1?那么有什么方法可以将 date1 转换为数字,然后再返回到等于 date1 的 date2?

The problem is the usage of timeIntervalSince1970 .问题是timeIntervalSince1970的使用。 If you use this, the Date implementation will do some Double calculations to align it to the reference date (2001-01-01).如果您使用它, Date实现将进行一些Double计算以将其与参考日期 (2001-01-01) 对齐。

If you use timeIntervalSinceReferenceDate instead, this will be used directly, and your code should work then:如果您改用timeIntervalSinceReferenceDate ,这将直接使用,您的代码应该可以工作:

for i in 1...200000 {
    let date1 = Date()
    let date2 = Date(timeIntervalSinceReferenceDate: date1.timeIntervalSinceReferenceDate)
    if (date1 != date2) {
        // never called on my machine:
        let delta = date1.timeIntervalSince(date2)
        print("\(i): \(delta)")
    }
}

For your information, here the interesting parts of struct Date implementation on https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Date.swift - you see the calculation done in the first init :供您参考,这里是https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Date.swiftstruct Date实现的有趣部分 - 您会看到在第一个init完成的计算:

public struct Date : ReferenceConvertible, Comparable, Equatable {

    fileprivate var _time: TimeInterval
    public static let timeIntervalBetween1970AndReferenceDate: TimeInterval = 978307200.0

    public init(timeIntervalSince1970: TimeInterval) {
        self.init(timeIntervalSinceReferenceDate: timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate)
    }
    public init(timeIntervalSinceReferenceDate ti: TimeInterval) {
        _time = ti
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM