Created
April 18, 2020 15:29
-
-
Save nitin-agam/a5ce7ed3c0f9bc9b27be54ba6699174f to your computer and use it in GitHub Desktop.
This file contains 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 timeAgo() -> String { | |
let secondsAgo = Int(Date().timeIntervalSince(self)) | |
let minute = 60 | |
let hour = 60 * minute | |
let day = 24 * hour | |
let week = 7 * day | |
let month = 4 * week | |
let quotient: Int | |
let unit: String | |
if secondsAgo < minute { | |
quotient = secondsAgo | |
unit = "second" | |
} else if secondsAgo < hour { | |
quotient = secondsAgo / minute | |
unit = "min" | |
} else if secondsAgo < day { | |
quotient = secondsAgo / hour | |
unit = "hour" | |
} else if secondsAgo < week { | |
quotient = secondsAgo / day | |
unit = "day" | |
} else if secondsAgo < month { | |
quotient = secondsAgo / week | |
unit = "week" | |
} else { | |
quotient = secondsAgo / month | |
unit = "month" | |
} | |
return "\(quotient) \(unit)\(quotient == 1 ? "" : "s") ago" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment