Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A playground to get easy helpers for dates
//: Playground - noun: a place where people can play
import Foundation
extension DateComponents {
static prefix func - (components: DateComponents) -> DateComponents {
var newComponents = DateComponents()
newComponents.calendar = components.calendar
newComponents.timeZone = components.timeZone
if let year = components.year {
newComponents.year = -year
}
if let month = components.month {
newComponents.month = -month
}
if let day = components.day {
newComponents.day = -day
}
if let hour = components.hour {
newComponents.hour = -hour
}
if let minute = components.minute {
newComponents.minute = -minute
}
if let second = components.second {
newComponents.second = -second
}
if let nanosecond = components.nanosecond {
newComponents.nanosecond = -nanosecond
}
return newComponents
}
var ago: Date? {
let calendar = self.calendar ?? Calendar(identifier: .gregorian)
return calendar.date(byAdding: -self, to: Date())
}
var fromNow: Date? {
let calendar = self.calendar ?? Calendar(identifier: .gregorian)
return calendar.date(byAdding: self, to: Date())
}
}
extension Int {
var days: DateComponents {
var component = DateComponents()
component.day = self
return component
}
var day: DateComponents { return days }
var weeks: DateComponents {
var component = DateComponents()
component.day = self * 7
return component
}
var week: DateComponents { return weeks }
var months: DateComponents {
var component = DateComponents()
component.month = self
return component
}
var month: DateComponents { return months }
var seconds: DateComponents {
var component = DateComponents()
component.second = self
return component
}
var second: DateComponents { return seconds }
var minutes: DateComponents {
var component = DateComponents()
component.minute = self
return component
}
var minute: DateComponents { return minutes }
var hours: DateComponents {
var component = DateComponents()
component.hour = self
return component
}
var hour: DateComponents { return hours }
var years: DateComponents {
var component = DateComponents()
component.year = self
return component
}
var year: DateComponents { return years }
}
Date()
1.day.ago
3.days.ago
5.days.fromNow
1.month.ago
1.year.ago
3.years.ago
4.years.fromNow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment