Skip to content

Instantly share code, notes, and snippets.

@shirishbankar1
Created January 21, 2020 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirishbankar1/3827769804164446cef46915fea3a50d to your computer and use it in GitHub Desktop.
Save shirishbankar1/3827769804164446cef46915fea3a50d to your computer and use it in GitHub Desktop.
Calculate timespan from given date.
extension Date {
///*** Returns the amount of years from another date
func years(from date: Date) -> Int {
return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
}
///*** Returns the amount of months from another date
func months(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
///*** Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
///*** Returns the amount of days from another date
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
///*** Returns the amount of hours from another date
func hours(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
///*** Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
///*** Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
///*** Returns the amount of nanoseconds from another date
func nanoseconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.nanosecond], from: date, to: self).nanosecond ?? 0
}
///*** Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
if years(from: date) > 0 { return "\(years(from: date))y" }
if months(from: date) > 0 { return "\(months(from: date))M" }
if weeks(from: date) > 0 { return "\(weeks(from: date))w" }
if days(from: date) > 0 { return "\(days(from: date))d" }
if hours(from: date) > 0 { return "\(hours(from: date))h" }
if minutes(from: date) > 0 { return "\(minutes(from: date))m" }
if seconds(from: date) > 0 { return "\(seconds(from: date))s" }
if nanoseconds(from: date) > 0 { return "\(nanoseconds(from: date))ns" }
return ""
}
}
//*** Usage
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" //*** Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")//*** timezone in date string
let dateObject = dateFormatter.date(from: "2020-01-21")//*** Your date string
let years = Date().years(from: dateObject!)
var months = Date().months(from: dateObject!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment