Skip to content

Instantly share code, notes, and snippets.

@nunogoncalves

nunogoncalves/Dates.swift

Last active Feb 7, 2019
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Oni-zerone Oni-zerone commented Feb 7, 2019

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
You can’t perform that action at this time.