// utils/date.go // 日期辅助函数 package utils import ( "time" ) // GetCurrentYear 获取当前年份 func GetCurrentYear() int { return time.Now().Year() } // GetCurrentMonth 获取当前月份 func GetCurrentMonth() int { return int(time.Now().Month()) } // GetMonthLastDay 获取某年某月的最后一天 func GetMonthLastDay(year, month int) (yearOut, lastDay int) { // 使用time.Date构建该月第一天的日期 firstDay := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local) // 添加一个月,然后减去一天得到最后一天 lastDayDate := firstDay.AddDate(0, 1, -1) return lastDayDate.Year(), lastDayDate.Day() } // FormatDate 格式化日期为字符串 func FormatDate(t time.Time) string { return t.Format("2006-01-02") } // FormatDateTime 格式化日期时间为字符串 func FormatDateTime(t time.Time) string { return t.Format("2006-01-02 15:04:05") } // DurUntilTomorrowZero 计算当前时间到明天零点的间隔 func DurUntilTomorrowZero() time.Duration { now := time.Now() tomorrowZero := now.Truncate(24*time.Hour).AddDate(0, 0, 1) return tomorrowZero.Sub(now) } // GetSecondsUntilTomorrowZero 获取当前时间到明天零点之间的秒数 func GetSecondsUntilTomorrowZero() int64 { now := time.Now() // 今天零点 todayZero := now.Truncate(24 * time.Hour) // 明天零点 tomorrowZero := todayZero.AddDate(0, 0, 1) diff := tomorrowZero.Sub(now) // 转秒 return int64(time.Duration(diff.Seconds())) }