如何从 Date() 中提取今天、昨天并使其像工作日和月份一样本地化?

How to extract today, yesterday from Date() and make it localised like weekday and months?

我想从日期中提取今天、昨天,这样当我更改语言时它会自动本地化,就像工作日和月份发生的那样。

我正在使用的本地化日期代码:

let dateFormatter = Foundation.DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let dateStr = dateFormatter.string(from: datePickerView.date)
let timeStr = "00:00:00.000"

let dateString = NSString(format:"%@ %@",dateStr,timeStr)
let mainDF = Foundation.DateFormatter()
mainDF.dateFormat = "MMMM dd, yyyy hh:mm:ss.SSS"
mainDF.locale = Locale(identifier: "en_US_POSIX")
mainDF.timeZone = TimeZone(identifier: "UTC")
let date = mainDF.date(from: dateString as String)

如何实现?

DateFormatter has special flag for that: doesRelativeDateFormatting,使用为此格式化程序设置的区域设置,以相对格式呈现日期。

… If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow “tomorrow,” French may allow “the day after the day after tomorrow,” …

示例:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent // Using system locale
dateFormatter.doesRelativeDateFormatting = true // Enabling relative date formatting

// other dataFormatter settings here, irrelevant for example
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium

let now = Date() 
let dateString: String = dateFormatter.string(from: now)  
print("dateString: \(dateString)") // Prints `dateString: <Today in current locale>`