Skip to content

Instantly share code, notes, and snippets.

@josippetric
Created March 28, 2023 07:36
Show Gist options
  • Select an option

  • Save josippetric/381932507311fd8d5a125eeca37e7fd9 to your computer and use it in GitHub Desktop.

Select an option

Save josippetric/381932507311fd8d5a125eeca37e7fd9 to your computer and use it in GitHub Desktop.
Date Helpers
extension Date {
var age: Int {
get {
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: self, to: Date())
return ageComponents.year ?? 0
}
}
}
extension Date {
func addMonth(n: Int) -> Date {
let calendar = Calendar.current
return calendar.date(byAdding: .month, value: n, to: self)!
}
func addYear(n: Int) -> Date {
let calendar = Calendar.current
return calendar.date(byAdding: .year, value: n, to: self)!
}
func addDay(n: Int) -> Date {
let calendar = Calendar.current
return calendar.date(byAdding: .day, value: n, to: self)!
}
func addHours(n: Int) -> Date {
let calendar = Calendar.current
return calendar.date(byAdding: .hour, value: n, to: self)!
}
var monthName: String {
let calendar = Calendar.current
let monthInt = calendar.component(.month, from: self)
return calendar.monthSymbols[monthInt-1]
}
func months(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
func startOfMonth() -> Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
}
func endOfMonth() -> Date {
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())!
}
func getFirstNonWeekendDate() -> Date {
var nonWeekendDate = self
let calendar = Calendar.current
if calendar.isDateInWeekend(nonWeekendDate) {
nonWeekendDate = nonWeekendDate.addDay(n: 1)
if calendar.isDateInWeekend(nonWeekendDate) {
nonWeekendDate = nonWeekendDate.addDay(n: 1)
}
}
return nonWeekendDate.removeTimeStamp()
}
func removeTimeStamp() -> Date {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self)) else {
fatalError("Failed to strip time from Date object")
}
return date
}
func daysInMonths() -> Int {
let calendar = Calendar.current
let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
return numDays
}
/// Difference in seconds between two dates
static func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment