上下文
我在Date
上有一个自定义的Stringify Method
,它将给定的Date
格式化为String
。结果如下:
October 17th, 2022 at 1:27pm
但是,当Date
是Today
、Yesterday
或Tomorrow
时,我想用这个特定的String
描述来替换实际的Date
。结果应该是这样的:
Today at 1:27pm
代码
extension Date {
func stringify() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
return dateFormatter.string(from: self)
}
}
问题
- 既然
DateFormatter
不支持这种行为,我该如何实现这种行为
正如评论中所建议的,您可以使用DateFormatter
来实现这一点,诀窍是打开doesRelativeDateFormatting
标志。
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true
let todayString = dateFormatter.string(from: today)
print(todayString) // Today at 20:44
let yesterdayString = dateFormatter.string(from: yesterday)
print(yesterdayString) // Yesterday at 20:44
let tomorrowString = dateFormatter.string(from: tomorrow)
print(tomorrowString) // Tomorrow at 20:44