forked from shadowfacts/Tusker
64 lines
1.8 KiB
Swift
64 lines
1.8 KiB
Swift
//
|
|
// Date+TimeAgo.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 8/31/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
extension Date {
|
|
|
|
private static let unitFlags = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfYear, .month, .year])
|
|
|
|
func timeAgo() -> (Int, Calendar.Component) {
|
|
let calendar = NSCalendar.current
|
|
let components = calendar.dateComponents(Date.unitFlags, from: self, to: Date())
|
|
|
|
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)")
|
|
}
|
|
}
|
|
|
|
}
|