这是一个非常令人困惑的情况,我已经阅读了很多关于NSDateFormatter的文档,但我似乎无法设置本地化的日期格式模板。使用dateFormat属性可以工作,但使用setLocalizedDateFormatFromTemplate不起作用,本质上,我在WASTIVE5.3中有以下代码:
首先,在终端中打开一个快速REPL并键入以下内容:
import Foundation // takes a few secs
var ftt = DateFormatter()
ftt.locale = Locale(identifier: "en_US")
ftt.setLocalizedDateFormatFromTemplate("'Deliver on' MMMM d 'at' h:mm a 'sharp'")运行之后,我得到以下输出:
ftt: DateFormatter = {
baseNSFormatter@0 = {
baseNSObject@0 = {
isa = NSDateFormatter
}
}
_attributes = 3 key/value pairs {
[0] = {
key = "locale"
value =
}
[1] = {
key = "formatterBehavior"
value = Int64(1040)
}
[2] = {
key = "dateFormat"
value = "MMMM d, h:mm a"
}
}
_formatter = {}
_counter = 0
_cacheGeneration = 3
_behavior = 0
}从输出中可以看到,locale或dateFormat都没有存储。格式化日期会导致以下情况:
14> ftt.string(from: Date())
$R1: String = "October 21, 8:19 PM"我已经确保了地区标识符是正确的,我遵循了一些关于DateFormatter的教程,例如:
并检查setLocalizedDateFormatFromTemplate和苹果的文档的使用情况,并确保在设置locale后调用它。
如果直接分配dateFormat属性,就会得到所需的结果:
17> ftt.dateFormat = "'Deliver on' MMMM d 'at' h:mm a 'sharp'"
ftt: DateFormatter = {
baseNSFormatter@0 = {
baseNSObject@0 = {
isa = NSDateFormatter
}
}
_attributes = 3 key/value pairs {
[0] = {
key = "locale"
value =
}
[1] = {
key = "formatterBehavior"
value = Int64(1040)
}
[2] = {
key = "dateFormat"
value = "\'Deliver on\' MMMM d \'at\' h:mm a \'sharp\'"
}
}
_formatter =
_counter = 0
_cacheGeneration = 2
_behavior = 0
}
18> ftt.string(from: Date())
$R2: String = "Deliver on October 21 at 8:25 PM sharp"到底怎么回事?!我漏掉了什么明显的东西吗?我想了解他们的行为。
提前感谢!
发布于 2020-10-22 03:48:02
我想你误解了setLocalizedDateFormatFromTemplate的工作。其文件说:
调用此方法相当于(但不一定实现)将
dateFormat属性设置为调用dateFormat(fromTemplate:options:locale:)方法的结果,不传递选项和区域设置属性值。
现在dateFormat(fromTemplate:options:locale:)是做什么的?让我们看看:
返回值 表示模板中给出的日期格式组件的本地化日期格式字符串,为由区域设置指定的区域设置进行适当安排。 返回的字符串可能不完全包含模板中给出的组件,但可能--例如--应用了特定于地区的调整。
因此,dateFormat(fromTemplate:options:locale:)尝试将模板本地化到指定的地区。如果没有指定区域设置,则使用Locale.current。例如:
// this produces "MM/dd/yyyy"
DateFormatter.dateFormat(fromTemplate: "yyyy dd MM", options: 0, locale: Locale(identifier: "en-US"))这解释了为什么它删除所有引用的字符串的格式,因为本地化引擎不能识别您引用的字符串,所以要生成您的日期格式的“本地化”版本,它可以做的最好的就是删除它们。就它而言,引用的字符串可能是一种不同的语言!
所以这并不是说setLocalizedDateFormatFromTemplate没有改变dateFormat。它确实将其更改为"MMMM d, h:mm a",iOS认为这是格式最好的“本地化”版本。
"'Deliver on' MMMM d 'at' h:mm a 'sharp'"在这种情况下,您应该直接设置dateFormat,而不是setLocalizedDateFormatFromTemplate,因为您不需要本地化的日期格式。
发布于 2020-10-22 03:39:34
存在的问题是,模板中日期组件的顺序没有什么不同。您应该只传递组件,其显示方式取决于区域设置。
let ftt = DateFormatter()
ftt.locale = Locale(identifier: "en_US")
ftt.setLocalizedDateFormatFromTemplate("dMMMMhm")
ftt.dateFormat // "MMMM d, h:mm a"
ftt.string(from: Date()) // "October 22, 12:45 AM"
ftt.locale = Locale(identifier: "pt_BR")
ftt.setLocalizedDateFormatFromTemplate("MMMMdysmH")
ftt.dateFormat // "d 'de' MMMM 'de' y HH:mm:ss"
ftt.string(from: Date()) // "22 de outubro de 2020 00:45:36"https://stackoverflow.com/questions/64474883
复制相似问题