DateComponentsFormatter可以格式化小数秒吗?

16
我想要将值1.5打印成“1.5秒”,就像Safari的时间轴一样,我正在尝试使用DateComponentsFormatter来实现。
不幸的是,它的.allowedUnits只能达到.second(即使枚举中有.nanosecond)。我尝试设置.allowsFractionalUnits = true,但仍然得到“0秒”。
是否有办法从DateComponentsFormatter中获取小数秒?

你使用哪种方法来格式化什么? - Willeke
Willeke:唯一接受参数1.5的方法是:string(from: TimeInterval) - Ssswift
时间间隔在内部被转换为NSDateComponents。 - Willeke
Willeke:是的,我认为那就是情况所在。这是他们实现的逻辑方式。那又怎样? - Ssswift
你有找到一种方法从 DateComponentsFormatter 中获取 “1.5 秒” 的方式吗?难道苹果真的忘记实现这个功能了吗? - Daniel
1
@Daniel 很遗憾,这似乎非常真实,自 iOS 13.3以来。我没有找到一种从DateComponentsFormatter获取本地化输出“1.5秒”的方法。它只会输出“1.5”。非常烦人。 - Womble
1个回答

2

对于位置单位样式,可以使用DateComponentsFormatterNumberFormatter一起使用,以获得具有本地化功能的字符串。

func format(_ seconds: TimeInterval) -> String {
  let components = DateComponentsFormatter()
  components.allowedUnits = [.minute, .second]
  components.allowsFractionalUnits = true // does not work as expected
  components.unitsStyle = .positional
  components.zeroFormattingBehavior = .pad

  let fraction = NumberFormatter()
  fraction.maximumIntegerDigits = 0
  fraction.minimumFractionDigits = 0
  fraction.maximumFractionDigits = 3
  fraction.alwaysShowsDecimalSeparator = false

  let fractionalPart = NSNumber(value: seconds.truncatingRemainder(dividingBy: 1))

  return components.string(from: seconds)! + fraction.string(from: fractionalPart)!
}

print(Locale.current) // ru_RU (current)
print(format(600.5))  // 10:00,5 <- note locale specific decimal separator

不幸的是,对于其他日期格式使用此方法更加麻烦。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接