Skip to content

Instantly share code, notes, and snippets.

@mattjamesod
Created February 3, 2023 14:29
Show Gist options
  • Save mattjamesod/b546c7c96e36035d05bd5e552623e4ef to your computer and use it in GitHub Desktop.
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)
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