Tusker/Tusker/Extensions/Date+TimeAgo.swift

89 lines
2.7 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 {
// var timeAgo: String {
// let calendar = NSCalendar.current
// let unitFlags = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfYear, .month, .year])
//
// let components = calendar.dateComponents(unitFlags, from: self, to: Date())
//
// if components.year! >= 1 {
// return "\(components.year!)y"
// } else if components.month! >= 1 {
// return "\(components.month!)mo"
// } else if components.weekOfYear! >= 1 {
// return "\(components.weekOfYear!)w"
// } else if components.day! >= 1 {
// return "\(components.day!)d"
// } else if components.hour! >= 1 {
// return "\(components.hour!)h"
// } else if components.minute! >= 1 {
// return "\(components.minute!)m"
// } else if components.second! >= 3 {
// return "\(components.second!)s"
// } else {
// return "Now"
// }
// }
func timeAgo() -> (Int, Calendar.Component) {
let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfYear, .month, .year])
let components = calendar.dateComponents(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)")
}
}
}