如何将时间显示为“刚刚”“xx分钟前”这种格式呢,话不多少,上代码:
// 获取当前时间
let currentDate = Date()
// 目标时间
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let targetDate = formatter.date(from: dateStr) else { return "" }
let calendar = Calendar.current
let returnFormatter = DateFormatter()
// 先判断年份
if calendar.isDate(targetDate, equalTo: currentDate, toGranularity: .year) {
// 判断是否为今天
if calendar.isDateInToday(targetDate) {
let components = calendar.dateComponents([.minute, .hour], from: targetDate, to: currentDate)
// 判断小时
if components.hour == 0 {
// 判断分钟
if components.minute == 0 {
return "刚刚"
} else {
return "\(String(describing: components.hour))分钟前"
}
} else {
return "\(String(describing: components.hour))小时前"
}
} else if calendar.isDateInYesterday(targetDate) {
return "昨天"
} else {
returnFormatter.dateFormat = "MM.dd"
return returnFormatter.string(from: targetDate)
}
} else {
// 直接返回年月日
returnFormatter.dateFormat = "yyyy.MM.dd";
return returnFormatter.string(from: targetDate)
}