Last active
September 11, 2019 02:12
-
-
Save BrandonShega/e745ddb4d66a8efeabe504614fd58084 to your computer and use it in GitHub Desktop.
Relative Time
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
extension NSDate { | |
var relativeTime: String { | |
let calendar = NSCalendar.currentCalendar() | |
let components = calendar.components([.Second, .Minute, .Hour, .Day, .Month, .Year], fromDate: self, toDate: NSDate(), options: []) | |
if components.year > 0 { | |
if components.year < 2 { | |
return "Last year" | |
} else { | |
return "\(components.year) years ago" | |
} | |
} | |
if components.month > 0 { | |
if components.month < 2 { | |
return "Last month" | |
} else { | |
return "\(components.month) months ago" | |
} | |
} | |
if components.day >= 7 { | |
let week = components.day/7 | |
if week < 2 { | |
return "Last week" | |
} else { | |
return "\(week) weeks ago" | |
} | |
} | |
if components.day > 0 { | |
if components.day < 2 { | |
return "Yesterday" | |
} else { | |
return "\(components.day) days ago" | |
} | |
} | |
if components.hour > 0 { | |
if components.hour < 2 { | |
return "An hour ago" | |
} else { | |
return "\(components.hour) hours ago" | |
} | |
} | |
if components.minute > 0 { | |
if components.minute < 2 { | |
return "A minute ago" | |
} else { | |
return "\(components.minute) minutes ago" | |
} | |
} | |
if components.second > 0 { | |
if components.second < 5 { | |
return "Just now" | |
} else { | |
return "\(components.second) seconds ago" | |
} | |
} | |
return "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 3: