前系
time.AddDate(years, months, days) -1を渡すと前の日にも戻れる
// 昨日
t1 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t1.AddDate(0, 0, -1))
// ちゃんと月をまたげる
// => 2019-11-30 23:59:59.999999999 +0000 UTC
// 10日前
t2 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t2.AddDate(0, 0, -10))
// => 2019-11-21 23:59:59.999999999 +0000 UTC
// 1週間前
t3 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t3.AddDate(0, 0, -7))
// => 2019-11-24 23:59:59.999999999 +0000 UTC
// 1ヶ月前
t4 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t4.AddDate(0, -1, 0))
// => 2019-12-01 23:59:59.999999999 +0000 UTC
// 30日を引いてるだけに見える
後系
// 明日
t5 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t5.AddDate(0, 0, 1))
// => 2020-01-01 23:59:59.999999999 +0000 UTC
// 10日後
t6 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t6.AddDate(0, 0, 10))
// => 2020-01-10 23:59:59.999999999 +0000 UTC
// 1週間後
t7 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t7.AddDate(0,0,7))
// => 2020-01-07 23:59:59.999999999 +0000 UTC
// 1ヶ月後
t8 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t8.AddDate(0,1,0))
// => 2020-01-31 23:59:59.999999999 +0000 UTC
コピペ実行用
package main
import (
"fmt"
"time"
)
//--------------------------------------------------------
// 昨日、○日前、○週間前、○月前、明日、○週間後、○日後、○ヶ月後などを取得する(time.AddDate)
//--------------------------------------------------------
func main() {
// 前系
// time.AddDate(years, months, days)
// -1を渡すと前の日にも戻れる
// 昨日
t1 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t1.AddDate(0, 0, -1))
// ちゃんと月をまたげる
// => 2019-11-30 23:59:59.999999999 +0000 UTC
// 10日前
t2 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t2.AddDate(0, 0, -10))
// => 2019-11-21 23:59:59.999999999 +0000 UTC
// 1週間前
t3 := time.Date(2019, 12, 1, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t3.AddDate(0, 0, -7))
// => 2019-11-24 23:59:59.999999999 +0000 UTC
// 1ヶ月前
t4 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t4.AddDate(0, -1, 0))
// => 2019-12-01 23:59:59.999999999 +0000 UTC
// 30日を引いてるだけに見える
// 後系
// 明日
t5 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t5.AddDate(0, 0, 1))
// => 2020-01-01 23:59:59.999999999 +0000 UTC
// 10日後
t6 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t6.AddDate(0, 0, 10))
// => 2020-01-10 23:59:59.999999999 +0000 UTC
// 1週間後
t7 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t7.AddDate(0,0,7))
// => 2020-01-07 23:59:59.999999999 +0000 UTC
// 1ヶ月後
t8 := time.Date(2019, 12, 31, 23, 59, 59, 999999999, time.UTC)
fmt.Println(t8.AddDate(0,1,0))
// => 2020-01-31 23:59:59.999999999 +0000 UTC
}