【Swift】2つの日付差を秒で算出
どうも、ねこきち(@nekokichi1_yos2)です。
バックグラウンド対応のタイマーを作る際、タイマーが停止〜再起動、の時間を求めるのに役立ったので備忘録で残す。
参考:[Tips] Calendar を使用して日付の差や時間の差を求めるには?
http://swift.hiros-dot.net/?p=906#toc4
解説
使用するのは、CalederクラスのdateComponentsメソッド。
(ドキュメント://developer.apple.com/documentation/foundation/calendar/2292887-datecomponents)
let calender = Calendar.init(identifier: .gregorian) print(calender.dateComponents([.second], from: date1, to: date2))
そのまま出力すると、
second: 24 isLeapMonth: false
(isLeapMonth:閏月かどうかのBool値)
なので、.secondを付ける。
print(calender.dateComponents([.second], from: date1, to: date2).second)
注意点として、
- [.second]
- .second
と統一しないと、nilが返されるので、分ならminute、 時間ならhour、と統一すべし。
※補足
timeIntervalSince()でも日付差を算出できます。
date2.timeIntervalSince(date1)
しかも、timeIntervalSinceには、現在時刻との差を出す関数が酔いされてるので、むしろこっちの方が、すっきりしてて良いかも。
date2.timeIntervalSinceNow
ソースコード
import UIKit class timediff: UIViewController { //アプリ起動時の時刻 let date1 = Date() @IBAction func button(_ sender: Any) { //カレンダー let calender = Calendar.init(identifier: .gregorian) //ボタン押下時の時刻 let date2 = Date() //例:24秒(date1 - date2) //下記のどちらでも可 print(date2.timeIntervalSince(date1)) print(calender.dateComponents([.second], from: date1, to: date2).minute) } }