13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】日付の差分を計算する

Last updated at Posted at 2019-02-13

概要

この記事の手法は、@fromage-blanc さんの「日付の計算【Swift 3.0】」という記事における日付の差分計算に少し改良を加えたものです。

上記の記事では日付の差分計算を、 timeIntervalSince() で時間の差分(秒数)を取得して日数へと変換することで行なっています。

.swift
func calcDateRemainder(firstDate: Date, secondDate: Date? = nil) -> Int {

    var retInterval:Double!

    if secondDate == nil {
        retInterval = date?.timeIntervalSinceNow
    } else {
        retInterval = date?.timeIntervalSince(secondDate!)
    }

    let ret = retInterval/86400

    return Int(floor(ret))
}

しかし 1976-04-01 23:59:00 +00001976-04-02 00:00:00 +0000 のようなケースでも日付自体の差分を取得したい場合、秒数の差分から計算するだけではうまくいかないため少し改良が必要になります。

具体的には計算の前に少し前処理を入れてやる流れです。

前処理

前処理といっても難しい類のものではなく、単純に時間の情報をリセットするだけです。

.swift
func resetTime(date: Date) -> Date {
    let calendar: Calendar = Calendar(identifier: .gregorian)
    var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)

    components.hour = 0
    components.minute = 0
    components.second = 0
        
    return calendar.date(from: components)!
}

改良後

.swift
func calcDateRemainder(firstDate: Date, secondDate: Date? = nil) -> Int{

    var retInterval:Double!
    let firstDateReset = resetTime(date: firstDate)
        
    if secondDate == nil {
        let nowDate: Date = Date()
        let nowDateReset = resetTime(date: nowDate)
        retInterval = firstDateReset.timeIntervalSince(nowDateReset)
    } else {
        let secondDateReset: Date = resetTime(date: secondDate!)
        retInterval = firstDate.timeIntervalSince(secondDateReset)
    }
        
    let ret = retInterval/86400
        
    return Int(floor(ret))  // n日
}

timeIntervalSince() を使う前に前処理の resetTime() を挟んでやることで日付の情報のみから日数の差分が計算できるようになります。

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?