Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active April 7, 2016 20:51
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 dimpiax/ad4522d7fd7e100ad9f618f4649ad600 to your computer and use it in GitHub Desktop.
Save dimpiax/ad4522d7fd7e100ad9f618f4649ad600 to your computer and use it in GitHub Desktop.
Conversion timestamp to simple phrase interval
extension NSDate {
class func relativeTimeInString(value: NSTimeInterval) -> String {
func getTimeData(value: NSTimeInterval) -> (count: Int, suffix: String) {
let count = Int(floor(value))
let suffix = count != 1 ? "s" : ""
return (count: count, suffix: suffix)
}
let value = -value
switch value {
case 0...15: return "just now"
case 0..<60:
let timeData = getTimeData(value)
return "\(timeData.count) second\(timeData.suffix) ago"
case 0..<3600:
let timeData = getTimeData(value/60)
return "\(timeData.count) minute\(timeData.suffix) ago"
case 0..<86400:
let timeData = getTimeData(value/3600)
return "\(timeData.count) hour\(timeData.suffix) ago"
case 0..<604800:
let timeData = getTimeData(value/86400)
return "\(timeData.count) day\(timeData.suffix) ago"
default:
let timeData = getTimeData(value/604800)
return "\(timeData.count) week\(timeData.suffix) ago"
}
}
}
@dimpiax
Copy link
Author

dimpiax commented Apr 7, 2016

Usage:

let time = NSDate(timeIntervalSince1970: timestamp).timeIntervalSinceNow
let relativeTimeString = NSDate.relativeTimeInString(time)
print(relativeTimeString)

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