如果Swift中合适的话,如何格式化字符串以使用Today和Yesterday而不是Date



上下文

我在Date上有一个自定义的Stringify Method,它将给定的Date格式化为String。结果如下:

October 17th, 2022 at 1:27pm

但是,当DateTodayYesterdayTomorrow时,我想用这个特定的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

相关内容

  • 没有找到相关文章

最新更新