Created
April 4, 2017 00:12
-
-
Save jonathanduty/73bbe6ec9573df2fb4e244674f7ebaac to your computer and use it in GitHub Desktop.
HumanTime
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 HumanTime: NSObject { | |
| let minute = 1 | |
| let hour = 60 | |
| let day = 60 * 24 | |
| let week = 60 * 24 * 7 | |
| let now: Date | |
| convenience override init() { | |
| self.init(now: Date()) | |
| } | |
| init(now: Date) { | |
| self.now = now | |
| } | |
| func ageInWords(_ time: Date) -> String { | |
| let mins = Int(round(now.timeIntervalSince(time) / 60.0)) | |
| switch mins { | |
| case 0: | |
| return "just now" | |
| case 1..<hour: | |
| return formatMinutes(mins, withUnit: "min", divisor: minute) | |
| case hour..<day: | |
| return formatMinutes(mins, withUnit: "hour", divisor: hour) | |
| case day..<week: | |
| return formatMinutes(mins, withUnit: "day", divisor: day) | |
| default: | |
| return formatMinutes(mins, withUnit: "week", divisor: week) | |
| } | |
| } | |
| func formatMinutes(_ minutes: Int, withUnit unit: String, divisor: Int) -> String { | |
| let units = (minutes + divisor / 2) / divisor | |
| let plural = (units != 1) | |
| return "\(units) \(unit)\(plural ? "s" : "")" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment