Last active
February 3, 2018 23:09
-
-
Save Ben-G/365b17312067f2c2371b88218a76ea9d to your computer and use it in GitHub Desktop.
Date Equality Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Want to check equality of two Date instances *in your tests?* (you should never rely on this in | |
// production). Add this extension to avoid | |
// rounding errors when using different initializers. | |
// See: https://twitter.com/benjaminencz/status/794606769360076800 | |
extension Date { | |
public static func ==(lhs: Date, rhs: Date) -> Bool { | |
return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate || | |
lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970 | |
} | |
} | |
// --------------------------------------------------------------------------------------- | |
// "Test" | |
for i in 1...100 { | |
let refDate = Date() | |
let result = refDate == Date(timeIntervalSince1970: refDate.timeIntervalSince1970) | |
if !result { | |
// You will see an indeterminate, yet high, amount of "oh-oh"s without the extension above. | |
print("oh-oh \(i)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment