Skip to content

Instantly share code, notes, and snippets.

@atljeremy
Last active March 26, 2017 18:47
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atljeremy/7681cbad00a2c71803b3 to your computer and use it in GitHub Desktop.
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
/*
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)
}
}
@alexszilagyi
Copy link

I think there's a typo error on these lines:

var minutes: NSTimeInterval {
    let secondsInAMinute = 60 as NSTimeInterval
    return self * secondsInAMinute
}

you need to use the secondsInAMinute variable.

@basememara
Copy link

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