Skip to content

Instantly share code, notes, and snippets.

@nunogoncalves
Last active February 7, 2019 15:10
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunogoncalves/2cb7c7788a8f017e124d84a22c43e7fd to your computer and use it in GitHub Desktop.
Save nunogoncalves/2cb7c7788a8f017e124d84a22c43e7fd to your computer and use it in GitHub Desktop.
Date Operations in swift 3 //Date() + 1.days
//See the bottom of this file to check what you can do with this
let calendar = Calendar(identifier: .gregorian)
struct CalendarComponentAmount {
let component: Calendar.Component
let amount: Int
}
infix operator +: AdditionPrecedence
extension Date {
static func +(date: Date, componentAmount: CalendarComponentAmount) -> Date {
return calendar.date(byAdding: componentAmount.component,
value: componentAmount.amount,
to: date)!
}
}
extension Int {
var years: CalendarComponentAmount {
return CalendarComponentAmount(component: .year, amount: self)
}
var months: CalendarComponentAmount {
return CalendarComponentAmount(component: .month, amount: self)
}
var days: CalendarComponentAmount {
return CalendarComponentAmount(component: .day, amount: self)
}
var hours: CalendarComponentAmount {
return CalendarComponentAmount(component: .hour, amount: self)
}
var minutes: CalendarComponentAmount {
return CalendarComponentAmount(component: .minute, amount: self)
}
var seconds: CalendarComponentAmount {
return CalendarComponentAmount(component: .second, amount: self)
}
}
var d = Date() => "Nov 15, 2016, 4:17 PM"
d + 1.years => "Nov 15, 2017, 4:17 PM"
d + 2.months => "Jan 16, 2017, 4:17 PM"
d + 3.days => "Nov 18, 2016, 4:17 PM"
d + 4.hours => "Nov 15, 2016, 8:17 PM"
d + 5.minutes => "Nov 15, 2016, 4:22 PM"
d + 60.seconds => "Nov 15, 2016, 4:18 PM"
@Oni-zerone
Copy link

Great work, I really appreciate it, very Inspiring :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment