gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:35 25 4
gpt4 key购买 nike

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

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

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有特殊标志: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>`

关于ios - 如何从 Date() 中提取今天、昨天并使其像工作日和月份一样本地化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47975134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com