这里写自定义目录标题
Go打印一年内每个月的起始时间与终止时间
package main
import (
"fmt"
"time"
)
var timeFotmat = "2006-01-02 15:04:05"
func main() {
for i := 1; i <= 12; i++ {
start, end := GetMonthIntervalMapping(2022, i)
fmt.Printf(start + "\t" + end + "\n")
}
}
func GetMonthIntervalMapping(year int, month int) (string, string) {
now := time.Now()
date := now.AddDate(-now.Year()+year, int(-now.Month())+month+1, -now.Day())
start := GetFirstDateOfMonth(date).Format(timeFotmat)
end := GetLastDateOfMonth(date).Format(timeFotmat)
return start, end
}
func GetLastDateOfMonth(d time.Time) time.Time {
date := GetFirstDateOfMonth(d).AddDate(0, 1, -1)
date = date.Add(time.Hour*23 + time.Minute*59 + time.Second*59)
return date
}
func GetFirstDateOfMonth(d time.Time) time.Time {
d = d.AddDate(0, 0, -d.Day()+1)
return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
}
测试执行
2022-01-01 00:00:00 2022-01-31 23:59:59
2022-02-01 00:00:00 2022-02-28 23:59:59
2022-03-01 00:00:00 2022-03-31 23:59:59
2022-04-01 00:00:00 2022-04-30 23:59:59
2022-05-01 00:00:00 2022-05-31 23:59:59
2022-06-01 00:00:00 2022-06-30 23:59:59
2022-07-01 00:00:00 2022-07-31 23:59:59
2022-08-01 00:00:00 2022-08-31 23:59:59
2022-09-01 00:00:00 2022-09-30 23:59:59
2022-10-01 00:00:00 2022-10-31 23:59:59
2022-11-01 00:00:00 2022-11-30 23:59:59
2022-12-01 00:00:00 2022-12-31 23:59:59