time.weekday类型可以做运算,强制转int,会得到偏差数。
默认是 sunday 开始到 saturday 算 0,1,2,3,4,5,6
所以只有monday减去sunday的时候是正数,特殊处理下就可以了。
/**
获取本周周一的日期
*/
func getfirstdateofweek() (weekmonday string) {
now := time.now()
offset := int(time.monday - now.weekday())
if offset > 0 {
offset = -6
}
weekstartdate := time.date(now.year(), now.month(), now.day(), 0, 0, 0, 0, time.local).adddate(0, 0, offset)
weekmonday = weekstartdate.format("2006-01-02")
return
}
/**
获取上周的周一日期
*/
func getlastweekfirstdate() (weekmonday string) {
thisweekmonday := getfirstdateofweek()
timemonday, _ := time.parse("2006-01-02", thisweekmonday)
lastweekmonday := timemonday.adddate(0, 0, -7)
weekmonday = lastweekmonday.format("2006-01-02")
return
}