利用 DateComponentsFormatter 將秒數轉換為時分秒

製作像碼錶或計時器這樣的功能時,我們需要將秒數轉換為時分秒。這點數學還難不倒我們,比方秒數是 62410,只要懂得除法即可轉換。

let second = 62410let (minute, sec) = second.quotientAndRemainder(dividingBy: 60)let (hour, min) = minute.quotientAndRemainder(dividingBy: 60)let message = "\(hour):\(min):\(sec)"

但是如果數學課都在睡覺,不會除法,或是懶得寫那麼多程式呢 ?

沒關係,我們也可以請 DateComponentsFormatter 幫我們轉換。例如以下例子,formatter.string(from: second) 將從傳入的秒數生成格式時:分:秒的字串!

import Foundationlet formatter = DateComponentsFormatter()let second: TimeInterval = 62410let message = formatter.string(from: second)

除了時:分:秒的格式,我們還可以指定不同的格式,例如以下例子:

以空白分隔,顯示時分秒的縮寫。

formatter.unitsStyle = .abbreviated

以空白分隔,顯示時分秒的完整字串。

formatter.unitsStyle = .full

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com