在开发中有时需要显示类似“1小时前”发布这种,需要我们拿到时间进行计算
func compareCurrentTime(timeString: String) -> String? {
// 将字符串转成Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.locale = Locale(identifier: "cn")
guard let timeDate = dateFormatter.date(from: timeString) else { return nil }
// 计算与当前时间的时差
var timeInterval = timeDate.timeIntervalSinceNow
timeInterval = -timeInterval
let secondsInMinute: Double = 60
let minutesInHour: Double = 60
let hoursInDay: Double = 24
if timeInterval < secondsInMinute {
return "刚刚"
}
let minute = timeInterval / secondsInMinute
if minute < minutesInHour {
return "\(minute)分钟之前"
}
let hour = minute / minutesInHour
if hour < hoursInDay {
return "\(hour)小时之前"
}
let day = hour / hoursInDay
if day <= 1 {
dateFormatter.dateFormat = "HH:mm"
let time = dateFormatter.string(from: timeDate)
return "昨天 \(time)"
} else if day < 7 {
return "\(day)天之前"
} else {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let time = dateFormatter.string(from: timeDate)
return "昨天 \(time)"
}
}
随便搜索的一个代码(希望没错),可以看出比较麻烦。在 iOS 13
之后,Apple
提供了快捷的实现方式
// 使用RelativeDateTimeFormatter
let now = Date()
let date = Date(timeInterval: 300, since: now)
let rdf = RelativeDateTimeFormatter()
rdf.dateTimeStyle = .named
let string = rdf.localizedString(for: date, relativeTo: now)
print("string:\(string)")
let string1 = rdf.localizedString(fromTimeInterval: -(3600 * 24 * 1))
print("string1:\(string1)")
// 打印结果
// string:5分钟后
// string1:昨天
修改 rdf.dateTimeStyle
的值
rdf.dateTimeStyle = .numeric
// 打印结果
// string:5分钟后
// string1:1天前
方便是挺方便的,但是定制能力偏弱,如果对提示文字有特殊要求的话,还是需要自己实现
标签:timeInterval,return,string,提示,实现,rdf,let,小时,string1 From: https://www.cnblogs.com/4zjq/p/16729833.html