Skip to content

Instantly share code, notes, and snippets.

@Pretz
Last active January 8, 2016 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pretz/ad29a79b560aa8bedf26 to your computer and use it in GitHub Desktop.
Save Pretz/ad29a79b560aa8bedf26 to your computer and use it in GitHub Desktop.
// Playground - noun: a place where people can play
import Foundation
extension NSTimeInterval {
var seconds: NSTimeInterval {
return self
}
var minutes: NSTimeInterval {
return seconds * 60
}
var hours: NSTimeInterval {
return minute * 60
}
var days: NSTimeInterval {
return hour * 24
}
var weeks: NSTimeInterval {
return days * 7
}
var months: NSTimeInterval {
return days * 30
}
var years: NSTimeInterval {
return days * 365.25
}
// MARK: Convenient Aliases, so 1.week works
var second: NSTimeInterval {
return seconds
}
var minute: NSTimeInterval {
return minutes
}
var hour: NSTimeInterval {
return hours
}
var day: NSTimeInterval {
return days
}
var week: NSTimeInterval {
return weeks
}
var year: NSTimeInterval {
return years
}
}
extension NSTimeInterval {
var ago: NSDate {
return NSDate(timeIntervalSinceNow: -self)
}
var fromNow: NSDate {
return NSDate(timeIntervalSinceNow: self)
}
func since(_ date: NSDate = NSDate()) -> NSDate {
return date.dateByAddingTimeInterval(self)
}
func until(_ date: NSDate = NSDate()) -> NSDate {
return date.dateByAddingTimeInterval(-self)
}
}
extension NSDate: Comparable {
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
public func +(lhs: NSDate, rhs: NSTimeInterval) -> NSDate {
return lhs.dateByAddingTimeInterval(rhs)
}
public func +=(inout lhs: NSDate, rhs: NSTimeInterval) {
lhs = lhs + rhs
}
public func -(lhs: NSDate, rhs: NSTimeInterval) -> NSDate {
return lhs.dateByAddingTimeInterval(-rhs)
}
public func -=(inout lhs: NSDate, rhs: NSTimeInterval) {
lhs = lhs - rhs
}
let d1 = 2.days.ago
let d2 = (1.day * 2).ago
d1.timeIntervalSinceReferenceDate
d2.timeIntervalSinceReferenceDate
d1 == d2
//
var date = 1.hour.ago
date += 20.minutes
let range = 2.5.hours.ago...date
let test = range ~= 2.hours.ago
let jan2_2014 = NSDate(timeIntervalSince1970: 1388620800)
3.hours.since(jan2_2014)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment