go常用时间函数
// YesterdayDate 获取昨日
func YesterdayDate() string {
now := time.Now()
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, -1).Format("2006-01-02")
}
// WeekDate 获取本周第一天和本周最后一天
// weekType = 1 本周
// weekType = 2 上周
func WeekDate(weekType int) (weekStart string, weekEnd string) {
var offset, offsetStart, offsetEnd int
now := time.Now()
//初始化获取本周一
offset = int(time.Monday - now.Weekday())
if offset > 0 {
offset = -6
}
if weekType == 1 { //本周
offsetStart = offset
} else { //上周一
offsetStart = offset - 7
}
offsetEnd = 6 + offsetStart - 7 //返回时间是6天
weekStart = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offsetStart).Format("2006-01-02")
weekEnd = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offsetEnd).Format("2006-01-02")
return
}
// MonthDate 获取本月第一天和本月最后一天
// monthType = 1 本月
// monthType = 2 上月
func MonthDate(monthType int) (monthStart string, monthEnd string) {
var offsetMonthStart int
now := time.Now()
if monthType == 1 {
offsetMonthStart = 0
} else {
offsetMonthStart = -1
}
monthStart = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, offsetMonthStart, 0).Format("2006-01-02")
monthEnd = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, offsetMonthStart+1, -1).Format("2006-01-02")
return
}
// YearDate 获取本年第一天和本年最后一天
// yearType = 1 今年
// yearType = 2 去年
func YearDate(yearType int) (yearStart string, yearEnd string) {
var offsetYearStart int
now := time.Now()
if yearType == 1 {
offsetYearStart = 0
} else {
offsetYearStart = -1
}
yearStart = time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local).AddDate(offsetYearStart, 0, 0).Format("2006-01-02")
yearEnd = time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.Local).AddDate(offsetYearStart+1, 0, -1).Format("2006-01-02")
return
}
作者:admin 创建时间:2022-05-13 11:22
最后编辑:admin 更新时间:2023-04-10 15:46
最后编辑:admin 更新时间:2023-04-10 15:46