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

标签 ios swift localization nsdate nsdateformatter

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

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

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/

相关文章:

ios - 清除和退出按钮

ios - 在 SpriteKit 中使用加速度计移动和旋转 Sprite

iphone - 将 UIWebView-heavy iPhone 应用程序移植到 Mac

ios - 仅触摸 Swift3 中 SKSpriteNode 的非透明像素

ios - 在 flutter 中找不到“audioplayers/AudioplayersPlugin.h”文件

android - b 代表什么,b+sr+Latn 背后的语法是什么?

ios - "loadHTMLString"WKWebView 的高度宽度问题

ios - Swift 中的本地化 - 即使应用程序有多种语言,也将应用程序限制为一种语言

c# - 强类型、可本地化的 DisplayNameAttribute

ios - AutoLayout 按钮,渐变,不会调整到高度