Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active February 3, 2018 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/365b17312067f2c2371b88218a76ea9d to your computer and use it in GitHub Desktop.
Save Ben-G/365b17312067f2c2371b88218a76ea9d to your computer and use it in GitHub Desktop.
Date Equality Swift
// 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