1
0

More than 1 year has passed since last update.

Goで2つの日付間の日数を取得する

Posted at

概要

2つの日付間の日数を取得する処理を書く機会があったので備忘録的に書き残します。

実装

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Date(2021, 12, 28, 0, 0, 0, 0, time.Local)
    end := time.Date(2022, 1, 2, 0, 0, 0, 0, time.Local)
    // 日付間の日数を取得
    diffDays := end.Sub(start).Hours() / 24
    fmt.Println(diffDays)

    // 日数分処理を行う
    for i := 0; i <= int(diffDays); i++ {
        addDate := start.AddDate(0, 0, i)
        fmt.Println(addDate)
        // ...処理
    }
}

↑を実行すると出力結果は以下のようになります。

5
2021-12-28 00:00:00 +0000 UTC
2021-12-29 00:00:00 +0000 UTC
2021-12-30 00:00:00 +0000 UTC
2021-12-31 00:00:00 +0000 UTC
2022-01-01 00:00:00 +0000 UTC
2022-01-02 00:00:00 +0000 UTC

解説

まず、 end.Sub(start)で2つの日付の差分を取得します。
Subメソッドの定義は以下のようになっていて、Duration型が返ってきます。

func (t Time) Sub(u Time) Duration

Durationの定義はint64のエイリアス型になっていて、時間を取得するHours()メソッドが定義されています。

type Duration int64

func (d Duration) Hours() float64

Hours()メソッドで取得した時間を1日の時間(=24)で割ってあげれば差の日数が取得できます。

end.Sub(start).Hours() / 24

参考

https://pkg.go.dev/time#Time.Sub
https://pkg.go.dev/time#Duration
https://pkg.go.dev/time#Duration.Hours

1
0
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
1
0