package utils
import (
"fmt"
"time"
)
// GetLastMonthDates 返回上个月的第一天和最后一天的time.Time类型值
func GetLastMonthDates(now time.Time) (time.Time, time.Time) {
var firstDay, lastDay time.Time
if now.Month() == 1 {
firstDay = time.Date(now.Year()-1, 12, 1, 0, 0, 0, 0, time.UTC)
} else {
firstDay = time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, time.UTC)
}
lastDay = firstDay.AddDate(0, 1, -1)
return firstDay, lastDay
}
// GetLastMonthDatesFormat 返回一个字符串切片,包含上个月的起始日期和结束日期,格式为传入的format
// format:时间格式字符串,如"2006-01-02"
// 返回值:
// - string:上个月的起始日期,按照format格式化
// - string:上个月的结束日期,按照format格式化
func GetLastMonthDatesFormat(now time.Time, format string) (string, string) {
firstDay, lastDay := GetLastMonthDates(now)
return firstDay.Format(format), lastDay.Format(format)
}
// GetMonthDays 根据给定的年月字符串返回该月有多少天
//
// 参数:
//
// yearMonth string - 表示年月的字符串,格式为"200601"
//
// 返回值:
//
// int - 表示该月有多少天
// error - 如果输入的年月格式不正确或解析出错,则返回错误信息;否则为nil
func GetMonthDays(yearMonth, layout string) (int, error) {
if len(yearMonth) != len(layout) {
return -1, fmt.Errorf("invalid date")
}
t, err := time.Parse(layout, yearMonth)
if err != nil {
return -1, err
}
return t.AddDate(0, 1, -t.Day()).Day(), nil
}
go在工作中常用的日期处理函数,复制即可使用
最新推荐文章于 2024-09-19 15:49:02 发布