【问题标题】:Swift: Formatting time string based on number of secondsSwift:根据秒数格式化时间字符串
【发布时间】:2016-09-30 10:19:33
【问题描述】:

我的应用中有一个 NSTimer 对象,它以秒为单位计算经过的时间。

我想以符合众所周知的标准的方式在我的应用程序界面中格式化 UILabel。

示例

00:01 - 一秒

01:00 - 60 秒

01:50:50 - 6650 秒

我想知道如何做到这一点,你知道任何基于 Int 秒数创建此类字符串的 pod/库吗?

显然我可以自己提出一个复杂的方法,但由于建议不要重新发明轮子,我更喜欢使用一些现成的解决方案。

我在 Foundation 库和 HealthKit 中都没有找到任何相关内容

您对如何完成它有什么建议吗?如果你说“自己去写” - 没关系。但我想确保我没有遗漏任何简单、直接的解决方案。

提前致谢

【问题讨论】:

  • @EricAya 谢谢!你能提供一个在我的案例中使用的例子吗?非常感谢

标签: ios swift nsdate nstimer


【解决方案1】:

(NS)DateComponentsFormatter 可以做到:

func timeStringFor(seconds : Int) -> String
{
  let formatter = DateComponentsFormatter()
  formatter.allowedUnits = [.second, .minute, .hour]
  formatter.zeroFormattingBehavior = .pad
  let output = formatter.string(from: TimeInterval(seconds))!
  return seconds < 3600 ? output.substring(from: output.range(of: ":")!.upperBound) : output
}

print(timeStringFor(seconds:1)) // 00:01
print(timeStringFor(seconds:60)) // 01:00
print(timeStringFor(seconds:6650)) // 1:50:50

【讨论】:

  • 这是一个非常有趣的方式,但很难想出:)
【解决方案2】:

根据this的回答想出来,很简单!

func createTimeString(seconds: Int)->String
{
    var h:Int = seconds / 3600
    var m:Int = (seconds/60) % 60
    var s:Int = seconds % 60
    let a = String(format: "%u:%02u:%02u", h,m,s)
    return a

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多