DateComponentsFormatter 和 .nanosecond

Gui*_*lla 3 time nsdateformatter nsdatecomponents swift nsdatecomponentsformatter

DateComponentsFormatter因此,我在只需要格式化给定 的纳秒的情况下使用 a TimeInterval。问题是它不能按预期工作,或者我在这里混淆了一些我不知道的东西。

这里有 3 个快速测试来说明我所说的内容。

第一个场景

let fooFormatter = DateComponentsFormatter()

fooFormatter.allowedUnits = [.second, .nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.collapsesLargestUnit = true
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.42424242424242424242424242424242))
Run Code Online (Sandbox Code Playgroud)

输出Optional("42 seconds")

预期:因为这会折叠“最大单位”(在本例中为秒),所以预计会类似于(Optional("42.42424242424242424242424242424242 * 1e^9"))

场景二

let fooFormatter = DateComponentsFormatter()

fooFormatter.allowedUnits = [.second, .nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.42))
Run Code Online (Sandbox Code Playgroud)

输出Optional("42 seconds")

预期:即使没有选择不崩溃.second,我的预期也接近(Optional("42 seconds 0.42 * 1e^9 nanoseconds"))

第三个场景

let fooFormatter = DateComponentsFormatter()
fooFormatter.allowedUnits = [.nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.424242))
Run Code Online (Sandbox Code Playgroud)

输出nil

预期:现在它甚至不会识别TimeInterval有效 - 当它被定义为可能的最小分数时 - 并且显然期望一切以纳秒为单位。

值得注意的是,我已经使用了allowsFractionalUnits = true,这更令人担忧,因为这种行为在上面给出的输出中也不起作用(请参阅此处的预期行为)。

提前致谢。

Rob*_*Rob 5

DateComponentsFormatter不支持纳秒。

请参阅 的文档allowedUnits,其中不包括纳秒。它说:

允许的日历单位是:

  • year
  • month
  • weekOfMonth
  • day
  • hour
  • minute
  • second

将任何其他日历单位分配给此属性都会导致异常。