Created
May 9, 2020 17:38
-
-
Save theevo/997aabc1dba37c2f24eb2cf477a81822 to your computer and use it in GitHub Desktop.
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
| import Foundation | |
| extension Date { | |
| func timeAgoString() -> String { | |
| let units = Array<Calendar.Component>([.year, .month, .day, .hour, .minute, .second]) | |
| let components = Calendar.current.dateComponents(Set(units), from: self, to: Date()) | |
| for unit in units | |
| { | |
| guard let value = components.value(for: unit) else { | |
| continue | |
| } | |
| if value == 1 { | |
| return "\(value) \(unit) ago" | |
| } else if value > 1 { | |
| return "\(value) \(unit)s ago" | |
| } | |
| } | |
| return "some time ago" | |
| } | |
| } | |
| let date: Date! = DateComponents(calendar: Calendar.current, year: 2020, month: 5, day: 9, hour: 9, minute: 55).date | |
| print(date.timeAgoString()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment