なんで3月の1ヶ月前がそうなるのという気持ち
package main import ( "fmt" "time" ) func main() { dateList := []string{"2022-05-31", "2022-04-30", "2022-03-31", "2022-02-28", "2022-01-31"} fmt.Println("# 1ヶ月前") for _, d := range dateList { t, _ := time.Parse("2006-01-02", d) fmt.Printf("%v -> %v\n", d, t.AddDate(0, -1, 0).Format("2006-01-02")) } fmt.Println("") fmt.Println("# 30日前") for _, d := range dateList { t, _ := time.Parse("2006-01-02", d) fmt.Printf("%v -> %v\n", d, t.AddDate(0, 0, -30).Format("2006-01-02")) } }
結果
# 1ヶ月前 2022-05-31 -> 2022-05-01 2022-04-30 -> 2022-03-30 2022-03-31 -> 2022-03-03 2022-02-28 -> 2022-01-28 2022-01-31 -> 2021-12-31 # 30日前 2022-05-31 -> 2022-05-01 2022-04-30 -> 2022-03-31 2022-03-31 -> 2022-03-01 2022-02-28 -> 2022-01-29 2022-01-31 -> 2022-01-01