DateComponentsFormatter和.nanosecond

问题描述 投票:1回答:1

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

这里有3个快速测试来说明我在说什么。

第一种情景

let fooFormatter = DateComponentsFormatter()

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

print(fooFormatter.string(from: 42.42424242424242424242424242424242))

输出: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))

输出: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))

输出:nil

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

重要的是要注意到我使用了allowsFractionalUnits = true,这更令人担忧,因为这种行为在上面给出的输出中也不起作用(参见预期的行为here)。

提前致谢。

swift time nsdateformatter nsdatecomponents nsdatecomponentsformatter
1个回答
2
投票

DateComponentsFormatter不支持纳秒。

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

允许的日历单位是:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.