golang 将开始时间和结束时间分割为周为单位
// 将开始时间和结束时间分割为周为单位
func GroupByWeekDate(startTime, endTime time.Time) []WeekDate {
weekDate := make([]WeekDate, 0)
diffDuration := endTime.Sub(startTime)
days := int(math.Ceil(float64(diffDuration/(time.Hour*24)))) + 1
currentWeekDate := WeekDate{}
_, _, currentWeekDate.WeekTh, _ = WeekByDate(endTime)
currentWeekDate.EndTime = endTime
currentWeekDay := int(endTime.Weekday())
if currentWeekDay == 0 {
currentWeekDay = 7
}
currentWeekDate.StartTime = endTime.AddDate(0, 0, -currentWeekDay+1)
nextWeekEndTime := currentWeekDate.StartTime
weekDate = append(weekDate, currentWeekDate)
for i := 0; i < (days-currentWeekDay)/7; i++ {
weekData := WeekDate{}
weekData.EndTime = nextWeekEndTime.AddDate(0, 0, -1)
//fmt.Println(nextWeekEndTime.AddDate(0, 0, -1))
weekData.StartTime = nextWeekEndTime.AddDate(0, 0, -7)
_, _, weekData.WeekTh, _ = WeekByDate(weekData.StartTime)
nextWeekEndTime = weekData.StartTime
weekDate = append(weekDate, weekData)
}
if lastDays := (days - currentWeekDay) % 7; lastDays > 0 {
lastData := WeekDate{}
lastData.EndTime = nextWeekEndTime.AddDate(0, 0, -1)
lastData.StartTime = nextWeekEndTime.AddDate(0, 0, -lastDays)
_, _, lastData.WeekTh, _ = WeekByDate(lastData.StartTime)
weekDate = append(weekDate, lastData)
}
sort.Slice(weekDate, func(i, j int) bool {
return true
})
return weekDate
}
func WeekByDate(t time.Time) (y int, m int, w int, d string) {
yearDay := t.YearDay()
yearFirstDay := t.AddDate(0, 0, -yearDay+1)
firstDayInWeek := int(yearFirstDay.Weekday())
//今年第一周有几天
firstWeekDays := 1
if firstDayInWeek != 0 {
firstWeekDays = 7 - firstDayInWeek + 1
}
var week int
if yearDay <= firstWeekDays {
week = 1
} else {
if (yearDay-firstWeekDays)%7 > 0 {
week = (yearDay-firstWeekDays)/7 + 2
} else {
week = (yearDay-firstWeekDays)/7 + 1
}
}
m, _ = strconv.Atoi(t.Format("1"))
day := t.Format(LayoutDate)
//fmt.Println(t.Year(),m, week,day)
return t.Year(), m, week, day
}