Swift 添加/设置日期的era组件

Swift 添加/设置日期的era组件,swift,foundation,Swift,Foundation,我使用基金会的日历类型的这些功能: date(通过添加:value:to:wrappingComponents:) date(通过设置:value:of:) 除了使用.era组件外,它们工作正常 var calendar = Calendar(identifier: .iso8601) calendar.locale = Locale(identifier: "en") calendar.timeZone = TimeZone(identifier: "GMT")! let formatte

我使用基金会的
日历
类型的这些功能:

  • date(通过添加:value:to:wrappingComponents:)
  • date(通过设置:value:of:)
除了使用
.era
组件外,它们工作正常

var calendar = Calendar(identifier: .iso8601)
calendar.locale = Locale(identifier: "en")
calendar.timeZone = TimeZone(identifier: "GMT")!
let formatter = DateFormatter()
formatter.calendar = calendar
formatter.timeZone = calendar.timeZone
formatter.dateFormat = "G yyyy/MM/dd HH:mm:ss.SSS zzz"

let date = formatter.date(from: "AD 2019/01/10 20:43:03.752 GMT")!

if let result = calendar.date(byAdding: .era, value: 1, to: date, wrappingComponents: true) {
  print(formatter.string(from: result))
} else {
  print("no result")
}

if let result = calendar.date(bySetting: .era, value: 0, of: date) {
  print(formatter.string(from: result))
} else {
  print("no result")
}
此代码给出了以下结果:

AD 2019/01/10 20:43:03.752 GMT
no result
添加era只会返回相同的日期,即使
wrappingComponents
设置为true,并且设置era不会产生任何结果

我查看了这些方法的文档,但他们没有说是这样或为什么


我做错了什么?

如果在日期字符串中将
AD
更改为
BC
,则调用
date(通过设置:value:of:)
返回原始日期,而不是“无结果”。奇怪的是你不能改变这个时代,你是对的。将值更改为1时也是如此。我猜,如果您将它设置为已设置的纪元,它将返回相同的日期,如果它是不同的纪元,则不会返回结果。然而,
calendar.maximumRange(of:.era)
返回
Range(0..经过更多的测试,如果新纪元>=旧纪元,设置似乎是有效的。至于添加,如果我将
wrappingComponents
设置为
true
,我会认为它总是有效的。这对我来说非常困惑。你认为添加纪元意味着什么?公历只有两个纪元(公元前和公元前)每一个都有无限的持续时间。