代码之家  ›  专栏  ›  技术社区  ›  Nicolas Gimelli

如何使用`Duration.TimeFormatStyle在swift中以“h m s”格式格式化时间`

  •  0
  • Nicolas Gimelli  · 技术社区  · 2 年前

    我写了一个扩展 TimeInterval 它返回一个格式为“h m s”的字符串。例如,5小时33分15秒将被写成“5小时33米15秒”。这是代码:

    extension TimeInterval {
      init(hours: Int, minutes: Int, seconds: Int) {
        self = Double(hours * 3600 + minutes * 60 + seconds)
      }
    
      func toString() -> String {
        let totalSeconds = Int(self)
        let hours = totalSeconds / 3600
        let minutes = (totalSeconds % 3600) / 60
        let seconds = totalSeconds % 60
    
        if hours >= 1 {
          return "\(hours)h \(minutes)m"
        } else if minutes >= 1 {
          return "\(minutes)m \(seconds)s"
        } else {
          return "\(seconds)s"
        }
      }
    }
    

    我想使用苹果的 Duration.TimeFormatStyle 时尚例如,我可以执行以下操作:

    let style = Duration.TimeFormatStyle(pattern: .hourMinuteSecond)
    var formattedTime = Duration.seconds(someInterval).formatted(style)
    

    我认为这比写 toString() 作为的扩展 时间间隔 ,但我不知道如何创建这种风格。任何指导都会很棒。

    2 回复  |  直到 2 年前
        1
  •  1
  •   Leo Dabus    2 年前

    你要找的是 Duration UnitsFormatStyle 宽度窄的单元:

    let duration: Duration = .seconds(15 + 33 * 60 + 5 * 3600)
    let string = duration.formatted(.units(width: .narrow)) // "5h 33m 15s"
    
        2
  •  0
  •   Sweeper    2 年前

    您可以使用 units 格式样式。

    从您的 toString 代码,看起来像

    • 您只想显示小时、分钟和秒的单位
    • 一次显示不超过2个单元
    • 即使单位为0,也显示“0”

    因此,您可以将这些选项传递给 单位 :

    let formattedTime = Duration.seconds(someDuration).formatted(
        .units(
            // by default, the allowed units are hour, minute and second
            width: .narrow, // for the h, m, s unit names
            maximumUnitCount: 2, // show no more than 2 units
            zeroValueUnits: .show(length: 1) // show 0s as "0"
        )
    )
    
    推荐文章