Tusker/Tusker/Extensions/Date+TimeAgo.swift

64 lines
1.8 KiB
Swift
Raw Normal View History

2018-08-31 17:46:33 +00:00
//
// Date+TimeAgo.swift
// Tusker
//
// Created by Shadowfacts on 8/31/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import Foundation
extension Date {
2020-02-29 00:24:14 +00:00
private static let unitFlags = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfYear, .month, .year])
2018-08-31 17:46:33 +00:00
func timeAgo() -> (Int, Calendar.Component) {
let calendar = NSCalendar.current
let components = calendar.dateComponents(Date.unitFlags, from: self, to: Date())
2018-08-31 17:46:33 +00:00
if components.year! >= 1 {
return (components.year!, .year)
} else if components.month! >= 1 {
return (components.month!, .month)
} else if components.weekOfYear! >= 1 {
return (components.weekOfYear!, .weekOfYear)
} else if components.day! >= 1 {
return (components.day!, .day)
} else if components.hour! >= 1 {
return (components.hour!, .hour)
} else if components.minute! >= 1 {
return (components.minute!, .minute)
} else {
return (components.second!, .second)
}
}
func timeAgoString() -> String {
let (amount, component) = timeAgo()
switch component {
case .year:
return "\(amount)y"
case .month:
return "\(amount)mo"
case .weekOfYear:
return "\(amount)w"
case .day:
return "\(amount)d"
case .hour:
return "\(amount)h"
case .minute:
return "\(amount)m"
case .second:
if amount >= 3 {
return "\(amount)s"
} else {
return "Now"
}
default:
fatalError("Unexpected component: \(component)")
}
}
}