gpt4 book ai didi

swift - DateComponentsFormatter 和 .nanosecond

转载 作者:搜寻专家 更新时间:2023-11-01 06:54:18 24 4
gpt4 key购买 nike

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

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

第一个场景

let fooFormatter = DateComponentsFormatter()

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

print(fooFormatter.string(from: 42.42424242424242424242424242424242))

输出:可选(“42 秒”)

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

第二个场景

let fooFormatter = DateComponentsFormatter()

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

print(fooFormatter.string(from: 42.42))

输出:可选(“42 秒”)

预计:即使没有选择不折叠 .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))

输出:

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

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

提前致谢。

最佳答案

DateComponentsFormatter 不支持纳秒。

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

The allowed calendar units are:

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

Assigning any other calendar units to this property results in an exception.

关于swift - DateComponentsFormatter 和 .nanosecond,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54710104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com