Skip to content

Instantly share code, notes, and snippets.

@shanev
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save shanev/534aa83189a2a96393b6 to your computer and use it in GitHub Desktop.

Select an option

Save shanev/534aa83189a2a96393b6 to your computer and use it in GitHub Desktop.
"Short time ago" function for Swift (based on https://github.com/MatthewYork/DateTools)
func shortTimeAgoSinceDate(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond
let now = NSDate()
let earliest = now.earlierDate(date)
let latest = (earliest == now) ? date : now
let components:NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: nil)
if (components.year >= 1) {
return "\(components.year)y"
} else if (components.month >= 1) {
return "\(components.month)m"
} else if (components.weekOfYear >= 1) {
return "\(components.weekOfYear)w"
} else if (components.day >= 1) {
return "\(components.day)d"
} else if (components.hour >= 1) {
return "\(components.hour)h"
} else if (components.minute >= 1) {
return "\(components.minute)m"
} else if (components.second >= 3) {
return "\(components.second)s"
} else {
return "now"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment