
顯示時間需求.jpg
廢話沒有,直接看代碼
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