Last active
March 26, 2017 18:47
-
-
Save atljeremy/7681cbad00a2c71803b3 to your computer and use it in GitHub Desktop.
Swift extension on NSTimeInterval and NSDate to make NSDate Comparable and to make working with dates in general more concise
This file contains hidden or 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
/* | |
Examples: | |
var date: NSDate | |
date = 10.seconds.fromNow | |
date = 30.minutes.ago | |
date = 2.days.from(someDate) | |
date = NSDate() + 3.days | |
if dateOne < dateTwo { | |
// dateOne is older than dateTwo | |
} | |
if dateOne > dateTwo { | |
// dateOne is more recent than dateTwo | |
} | |
if dateOne <= dateTwo { | |
// dateOne is older than or equal to dateTwo | |
} | |
if dateOne >= dateTwo { | |
// dateOne is more recent or equal to dateTwo | |
} | |
if dateOne == dateTwo { | |
// dateOne is equal to dateTwo | |
} | |
*/ | |
extension NSDate: Comparable { | |
} | |
func + (date: NSDate, timeInterval: NSTimeInterval) -> NSDate { | |
return date.dateByAddingTimeInterval(timeInterval) | |
} | |
public func ==(lhs: NSDate, rhs: NSDate) -> Bool { | |
if lhs.compare(rhs) == .OrderedSame { | |
return true | |
} | |
return false | |
} | |
public func <(lhs: NSDate, rhs: NSDate) -> Bool { | |
if lhs.compare(rhs) == .OrderedAscending { | |
return true | |
} | |
return false | |
} | |
extension NSTimeInterval { | |
var second: NSTimeInterval { | |
return self.seconds | |
} | |
var seconds: NSTimeInterval { | |
return self | |
} | |
var minute: NSTimeInterval { | |
return self.minutes | |
} | |
var minutes: NSTimeInterval { | |
let secondsInAMinute = 60 as NSTimeInterval | |
return self * minutesInASecond | |
} | |
var day: NSTimeInterval { | |
return self.days | |
} | |
var days: NSTimeInterval { | |
let secondsInADay = 86_400 as NSTimeInterval | |
return self * secondsInADay | |
} | |
var fromNow: NSDate { | |
let timeInterval = self | |
return NSDate().dateByAddingTimeInterval(timeInterval) | |
} | |
func from(date: NSDate) -> NSDate { | |
let timeInterval = self | |
return date.dateByAddingTimeInterval(timeInterval) | |
} | |
var ago: NSDate { | |
let timeInterval = self | |
return NSDate().dateByAddingTimeInterval(-timeInterval) | |
} | |
} |
Should be divided by instead of multiplied as well.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there's a typo error on these lines:
you need to use the secondsInAMinute variable.