Skip to content

Instantly share code, notes, and snippets.

@markiv
Created January 29, 2022 15:26
Show Gist options
  • Save markiv/2dc2b2e89d444844f7b4b1e77f744875 to your computer and use it in GitHub Desktop.
Save markiv/2dc2b2e89d444844f7b4b1e77f744875 to your computer and use it in GitHub Desktop.
Convenience initializers and helpers for Foundation Dates
import Foundation
extension Calendar {
static let gregorian = Calendar(identifier: .gregorian)
}
extension TimeZone {
static let utc = TimeZone(secondsFromGMT: 0)
}
extension Date {
/// Enumeration of the days of the week in the Gregorian calendar.
enum DayOfWeek: Int {
case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
}
/// Creates a date in the Gregorian calendar and UTC timezone.
init?(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
let components = DateComponents(
calendar: .gregorian, timeZone: .utc,
year: year, month: month, day: day, hour: hour, minute: minute, second: second
)
guard components.isValidDate, let date = components.date else { return nil }
self = date
}
/// Convenience shorthand initializer for a date in the Gregorian calendar and UTC timezone.
init?(_ year: Int, _ month: Int, _ day: Int) {
self.init(year: year, month: month, day: day)
}
/// The date's day of the week in the Gregorian calendar and UTC timezone.
var dayOfWeek: DayOfWeek? {
DayOfWeek(rawValue: Calendar.gregorian.component(.weekday, from: self))
}
/// Returns a new date by adding a component in the Gregorian calendar and UTC timezone.
func adding(_ value: Int, _ component: Calendar.Component = .day) -> Date? {
Calendar.gregorian.date(byAdding: component, value: value, to: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment