废话没有,直接看代码
extension NSDate {
//对时间的处理
//传入的时间戳精确到毫秒
public class func created_at(date:Double)->String{
let myDate = NSDate.init(timeIntervalSince1970: date / 1000 )
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
fmt.locale = NSLocale(localeIdentifier: "en_US") as Locale?
//获得当前时间
let now = NSDate()
//计算时间差
let interval = now.timeIntervalSince(myDate as Date)
// 处理小于一分钟的时间
if interval < 60 {
return "刚刚"
}
// 处理小于一小时的时间
if interval < 60 * 60 {
return "\(interval / 60)分钟前"
}
// 处理小于一天的时间
if interval < 60 * 60 * 24 {
return "\(interval / (60 * 60))小时前"
}
// 处理昨天时间
let calendar = Calendar.current
if calendar.isDateInYesterday(myDate as Date) {
fmt.dateFormat = "昨天 HH:mm"
let timeStr = fmt.string(from: myDate as Date)
return timeStr
}
//处理一年之内的时间
let cmp = calendar.dateComponents([.year,.month,.day], from: myDate as Date, to: now as Date)
if cmp.year! < 1 {
fmt.dateFormat = "MM-dd HH:mm"
let timeStr = fmt.string(from: myDate as Date)
return timeStr
}
//超过一年的时间
fmt.dateFormat = "yyyy-MM-dd HH:mm"
let timeStr = fmt.string(from: myDate as Date)
return timeStr
}
}
1B0221AF85DA4D4D89ABCFCD20ED7245.jpg
网友评论