秒数 ->時刻形式(HH:mm:ss)に変換する方法 – Swift4.0
カウントダウンタイマー的なコードを書く中で、秒数を日付単位に変換したくなり調べたので備忘録
サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
//そのままViewControllerに貼り付ければOK import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let formatter = DateComponentsFormatter() formatter.unitsStyle = .positional formatter.allowedUnits = [.minute,.hour,.second] let data = formatter.string(from: 10000.0) print("positional",data!) //short formatter.unitsStyle = .short let data2 = formatter.string(from: 10000.0) print("short",data2!) //brief formatter.unitsStyle = .brief let data3 = formatter.string(from: 10000.0) print("brief",data3!) //full formatter.unitsStyle = .full let data4 = formatter.string(from: 10000.0) print("full",data4!) //spellOut formatter.unitsStyle = .spellOut let data5 = formatter.string(from: 10000.0) print("spellOut",data5!) //abbreviated formatter.unitsStyle = .abbreviated let data6 = formatter.string(from: 10000.0) print("abbreviated",data6!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } |
デバッグエリアの出力内容
1 2 3 4 5 6 |
positional 2:46:40 short 2時間 46分 40秒 brief 2時間46分40秒 full 2時間 46分 40秒 spellOut 二時間 四十六分 四十秒 abbreviated 2h46m40s |
コードの説明
DateComponentsFormatterのunitsStyleを使うことで様々な形式に変換できます。
Shortとfullなどの違いが出ていないものもありますが、allowedUnitsを指定することで時間ではなく日時に変換することが可能なので、試してみてください。
なお、zeroFormattingBehaviorを指定まると、ある単位で値が0になるときの振る舞いも指定することができます。
また、Optionalなので「data!」とあんラップしていますが、何もつけないとOptional(“2:46:40”)となります。
日付が日本語にならない場合
アプリを海外対応させたいのであれば、ローカライズが必要になります。
簡易的に行うには下記で可能です。
・「info.plist」ファイルを選択
・一番上の方の「Localization native development region」 -> Value:「$(DEVELOPMENT_LANGUAGE)」を「Japan」にする
お知らせ

RealmSwift, Admobの動画・インステ・バナー広告、UICollectionView、iOS-Charts、UITableViewを使用しているので、是非ご利用ください!