Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"Time ago" function for Swift (based on MatthewYork's DateTools for Objective-C) *Swift 2
func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let earliest = now.earlierDate(date)
let latest = (earliest == now) ? date : now
let components:NSDateComponents = calendar.components([NSCalendarUnit.Minute , NSCalendarUnit.Hour , NSCalendarUnit.Day , NSCalendarUnit.WeekOfYear , NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Second], fromDate: earliest, toDate: latest, options: NSCalendarOptions())
if (components.year >= 2) {
return "\(components.year) years ago"
} else if (components.year >= 1){
if (numericDates){
return "1 year ago"
} else {
return "Last year"
}
} else if (components.month >= 2) {
return "\(components.month) months ago"
} else if (components.month >= 1){
if (numericDates){
return "1 month ago"
} else {
return "Last month"
}
} else if (components.weekOfYear >= 2) {
return "\(components.weekOfYear) weeks ago"
} else if (components.weekOfYear >= 1){
if (numericDates){
return "1 week ago"
} else {
return "Last week"
}
} else if (components.day >= 2) {
return "\(components.day) days ago"
} else if (components.day >= 1){
if (numericDates){
return "1 day ago"
} else {
return "Yesterday"
}
} else if (components.hour >= 2) {
return "\(components.hour) hours ago"
} else if (components.hour >= 1){
if (numericDates){
return "1 hour ago"
} else {
return "An hour ago"
}
} else if (components.minute >= 2) {
return "\(components.minute) minutes ago"
} else if (components.minute >= 1){
if (numericDates){
return "1 minute ago"
} else {
return "A minute ago"
}
} else if (components.second >= 3) {
return "\(components.second) seconds ago"
} else {
return "Just now"
}
}
@JoeyBodnar
Copy link

JoeyBodnar commented Dec 2, 2015

you are the real MVP.

@talalc
Copy link

talalc commented Dec 8, 2015

thanks so much, works great!

@pleasantlight
Copy link

pleasantlight commented Dec 25, 2015

Thanks!

Copy link

ghost commented Jan 27, 2016

Perfect ! Thank you very very much !

@arnaudlamy
Copy link

arnaudlamy commented Jun 13, 2016

@vitorspencer
Copy link

vitorspencer commented Jul 14, 2016

Man, this is awesome! Thanks a bunch for saving me the time to write it myself! 👍 😃

@dwipp
Copy link

dwipp commented Jul 28, 2016

Excellent!
Thanks bro.

@chashmeetsingh
Copy link

chashmeetsingh commented Aug 2, 2016

@msamoylov
Copy link

msamoylov commented Sep 19, 2016

Another variant of "time since" for Swift 3.

@tarekjradi
Copy link

tarekjradi commented Sep 29, 2016

Great code! Perfect. Thanks jacks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment