-
-
Save mattjamesod/b546c7c96e36035d05bd5e552623e4ef to your computer and use it in GitHub Desktop.
Extensions to Int and DateComponents that allow for Rails-style relative date syntax (i.e. 1.days.ago)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public extension Int { | |
var seconds: DateComponents { .init(second: self) } | |
var minutes: DateComponents { .init(minute: self) } | |
var hours: DateComponents { .init(hour: self) } | |
var days: DateComponents { .init(day: self) } | |
var weeks: DateComponents { .init(day: self * 7) } | |
var months: DateComponents { .init(month: self) } | |
var years: DateComponents { .init(year: self) } | |
} | |
public extension DateComponents { | |
var fromNow: Date? { | |
Calendar.current.date(byAdding: self, to: Date()) | |
} | |
var ago: Date? { | |
Calendar.current.date(byAdding: -self, to: Date()) | |
} | |
static prefix func -(rhs: Self) -> DateComponents { | |
.init( | |
year: -rhs.year, | |
month: -rhs.month, | |
day: -rhs.day, | |
hour: -rhs.hour, | |
minute: -rhs.minute, | |
second: -rhs.second | |
) | |
} | |
} | |
public extension Optional where Wrapped: Numeric { | |
static prefix func -(rhs: Self) -> Wrapped? { | |
switch rhs { | |
case .some(let value): | |
return value * -1 | |
case .none: | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment