Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active February 3, 2018 23:09
Show Gist options
  • 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.

Revisions

  1. Ben-G revised this gist Mar 23, 2017. 1 changed file with 18 additions and 1 deletion.
    19 changes: 18 additions & 1 deletion DateEquality.swift
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,23 @@
    // 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)")
    }
    }
  2. Ben-G created this gist Mar 23, 2017.
    6 changes: 6 additions & 0 deletions DateEquality.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    extension Date {
    public static func ==(lhs: Date, rhs: Date) -> Bool {
    return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate ||
    lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
    }
    }