Issue #833
Use RelativeDateTimeFormatter
. This assumes US locale is used
extension Date {
private static let relativeFormatter: RelativeDateTimeFormatter = {
let formatter = RelativeDateTimeFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.calendar?.locale = Locale(identifier: "en_US_POSIX")
formatter.dateTimeStyle = .numeric
formatter.unitsStyle = .abbreviated
return formatter
}()
var ago: String {
guard abs(timeIntervalSinceNow) > 60 else {
return "Just Now"
}
let text = Self.relativeFormatter.localizedString(for: self, relativeTo: Date())
return text
.replacingOccurrences(of: "ago", with: "")
.replacingOccurrences(of: "min", with: "m")
.replacingOccurrences(of: "hr", with: "h")
.replacingOccurrences(of: "day", with: "d")
.replacingOccurrences(of: "wk", with: "w")
.replacingOccurrences(of: "yr", with: "y")
.replacingOccurrences(of: " ", with: "")
.trimmingCharacters(in: .whitespaces)
}
}
struct Fake {
static let now = Date()
static let ago3m = now.addingTimeInterval(-3 * 60)
static let ago3h = now.addingTimeInterval(-3 * 60 * 60)
static let ago1d = now.addingTimeInterval(-1 * 24 * 60 * 60)
static let ago3w = now.addingTimeInterval(-3 * 7 * 24 * 60 * 60)
static let ago3mo = now.addingTimeInterval(-3 * 32 * 24 * 60 * 60)
static let ago2y = now.addingTimeInterval(-2 * 366 * 24 * 60 * 60)
}
Fake.now.ago // "Just Now"
Fake.ago3m.ago // "3m"
Fake.ago3h.ago // "3h"
Fake.ago1d.ago // "1d"
Fake.ago3w.ago // "3w"
Fake.ago3mo.ago // "3mo"
Fake.ago2y.ago // "2y"