Swift:根据秒数格式化时间字符串 [英] Swift: Formatting time string based on number of seconds

查看:78
本文介绍了Swift:根据秒数格式化时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is a NSTimer object in my app that counts elapsed time in seconds.

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

I want to format an UILabel in my app's interface in the such way it matches the well know standard.

示例

00:01 - 一秒

01:00 - 60 秒

01:00 - 60 seconds

01:50:50 - 6650 秒

01:50:50 - 6650 seconds

我想知道如何做到这一点,您知道任何基于 Int 秒数创建此类 String 的 Pod/库吗?

I wonder how to do that, do you know any pods/libraries that creates such String based on Int number of seconds?

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

Obviously I can come with a complicated method myself, but since it's recommended to not reinvent the wheel, I'd prefer to use some ready-to-use solution.

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

I haven't found anything relevant in Foundation library, nor in HealthKit

你对如何完成它有什么建议吗?如果你说自己去写吧"——那没问题.但我想确保我没有遗漏任何简单、直接的解决方案.

Do you have any suggestions how to get it done? If you say "go and write it yourself" - that's ok. But I wanted to be sure I'm not missing any simple, straightforward solution.

提前致谢

推荐答案

(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

这篇关于Swift:根据秒数格式化时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆