Skip to content

Instantly share code, notes, and snippets.

@nitin-agam
Created April 18, 2020 15:29
Show Gist options
  • Save nitin-agam/a5ce7ed3c0f9bc9b27be54ba6699174f to your computer and use it in GitHub Desktop.
Save nitin-agam/a5ce7ed3c0f9bc9b27be54ba6699174f to your computer and use it in GitHub Desktop.
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