Last active
March 30, 2018 05:55
-
-
Save iAmrSalman/d83cac43ecd0e25d5f08ac1dc3ed2aad to your computer and use it in GitHub Desktop.
[timeAgoSinceDate] #date #swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class func timeAgoSince(_ date: Date, from currentDate: Date = Date(), numericDates: Bool = false) -> String { | |
let calendar = Calendar.current | |
let now = currentDate | |
let earliest = (now as NSDate).earlierDate(date) | |
let latest = (earliest == now) ? date : now | |
let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: earliest, to: latest, options: NSCalendar.Options()) | |
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" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment