开发过程中经常会遇见需要对时间进行处理或者比较,以下为微博显示时间的时间比较,重点是当超过一天的时间比较,采用了Calendar(日历)类中的一些方法来处理,比较实用
/// 比较传入的字符串时间和当前时间
///
/// - Parameter createdAT: 字符串时间
/// - Returns: 比较结果
static func creatDateFromString(createdAT : String) -> String {
let fmt = DateFormatter()
fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
fmt.locale = Locale.init(identifier: "en")
guard let createdDate = fmt.date(from: createdAT) else {
return ""
}
let currentDate = Date()
let interval = currentDate.timeIntervalSince(createdDate)
if interval < 60 {
return "刚刚"
}
if interval < 60 * 60 {
let m = String(format: "%.0f", interval / 60)
return "\(m)分钟前"
}
if interval < 60 * 60 * 24 {
let m = String(format: "%.0f", interval / (60 * 60))
return "\(m)小时前"
}
// 日历
let calendar = Calendar.current
if calendar.isDateInYesterday(createdDate) {
fmt.dateFormat = "昨天 HH:mm"
let dateStr = fmt.string(from: createdDate)
return dateStr
}
let cmps = calendar.dateComponents([.year], from: createdDate, to: currentDate)
if cmps.year! < 1 {
fmt.dateFormat = "MM-dd HH:mm"
let dateStr = fmt.string(from: createdDate)
return dateStr
}
fmt.dateFormat = "yyyy-MM-dd HH:mm"
let dateStr = fmt.string(from: createdDate)
return dateStr
}
网友评论