【问题标题】:Format Int / TimeInterval with a custom format such as "1 h 20 m"使用自定义格式格式化 Int / TimeInterval,例如 \"1 h 20 m\"
【发布时间】:2022-11-10 22:08:42
【问题描述】:

我正在尝试将 Int / TimeInterval 格式化为 String 并具有以下所需输出:

Int(3600 + 600) formats to -> "1 h 10 m"

我尝试使用DateComponentsFormatter,它有一些预定义的格式,其中最接近的是.abbreviated,导致"1h 10m",但是在单位和它的值之间没有空格。

我还尝试使用新的.formattedRange 运算符,如下所示:.formatted(.components(style: .condensedAbbreviated, fields: [.hour, .minute])),这也导致"1h 10m",没有任何添加空格的选项。

最后我尝试使用Measurement<UnitDuration>.formatted 属性,但没有成功。

尝试使用DateIntervalFormatter 也无济于事。但是这种格式似乎并不适合手头的任务。

那么怎么办呢?

【问题讨论】:

    标签: swift formatting date-formatting nscalendar nsdatecomponents


    【解决方案1】:

    我没有看到一个简单的单线解决方案,我认为您需要使用具有自定义格式的标准DateFormatter

    let formatter = DateFormatter()
    formatter.dateFormat = "h 'h' m 'm'"
    

    然后像这样创建格式化程序需要的 Date 对象

    let date = Calendar.current.startOfDay(for: .now).addingTimeInterval(3600 + 600)
    
    
    let string = formatter.string(from: date)
    

    【讨论】:

    • 我认为这不是一个很好的解决方案,您基本上是在丢弃格式化程序的所有优点(主要是 h/m 单元的本地化)。还是我错了?
    • 你没有在你的问题中说任何关于本地化的内容,但我会看看。另外,本地化是什么意思,您想要一种非常非标准的格式,所以也许这更多是关于翻译而不是本地化。
    • 应该提到它,但是是的,使用硬编码Strings 不会削减它。感谢您调查它!
    • 另外,本地化是什么意思,您想要一种非常非标准的格式,所以也许这更多是关于翻译而不是本地化。
    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多