LoginSignup
1
2

More than 1 year has passed since last update.

【Go言語】翌月末を求める

Posted at

Go言語で翌月末を求める方法について記載してみました。

単純なAddDateではだめ

7/31の1ヵ月後

月を+1した場合に存在する日付の場合はOK。

t, _ := time.Parse("2006/01/02", "2023/07/31")
fmt.Println(t.AddDate(0, 1, 0))
// 出力
2023-08-31 00:00:00 +0000 UTC

8/31の1ヵ月後

月を+1した日付(9/31)は存在しない。
これを存在する値に変換する処理が走り10/1となります。(これをGoの正規化と呼びます)

t, _ := time.Parse("2006/01/02", "2023/08/31")
fmt.Println(t.AddDate(0, 1, 0))
// 出力
2023-10-01 00:00:00 +0000 UTC

月初の2ヵ月後の1日前を求めればよい

8/31の月初は8/1、その2ヵ月後は10/1。
その前日は9/30なので求めたかった翌月末となります。

t, _ := time.Parse("2006/01/02", "2023/08/31")
// 月初
t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
// 2ヵ月プラスし1日マイナス
fmt.Println(t.AddDate(0, 2, 0).AddDate(0, 0, -1))
// 出力
2023-09-30 00:00:00 +0000 UTC

The Go Playground

いろいろ試せるようにGo Playgroundに書いたコードをリンクしておきます。
https://go.dev/play/p/WChOkFZr6qs

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