这段程序是受困于当初写数据统计时有个非常变态的周统计需求,所以做了一个关于ISO周划分的函数
package awesome
import "time"
type WeekDate struct {
ISOYear int
ISOWeek int
StartTime time.Time
EndTime time.Time
}
func groupByWeekDate(startTime, endTime time.Time) []WeekDate {
// Sunday -> Saturday 0,1,2,3,4,5,6
startOffset := int(time.Monday - startTime.Weekday())
// 只有Monday减去Sunday的时候是正数
if startOffset > 0 {
startOffset = -6
}
startMonday := startTime.AddDate(0, 0, startOffset)
endOffset := int(7 - endTime.Weekday())
if endOffset == 7 {
endOffset = 0
}
endSunday := endTime.AddDate(0, 0, endOffset)
var res = make([]WeekDate, 0)
for i := startMonday; i.Before(endSunday) || i.Equal(endSunday); i = i.AddDate(0, 0, 7) {
iISOYear, iISOWeek := i.ISOWeek()
var tmp = WeekDate{
ISOYear: iISOYear,
ISOWeek: iISOWeek,
StartTime: i,
EndTime: i.AddDate(0, 0, 6),
}
res = append(res, tmp)
}
return res
}