golang 根据开始日期和结束日期计算出时间段内所有日期 分24小时时段
// GetBetweenDates 根据开始日期和结束日期计算出时间段内所有日期
// 参数为日期格式,如:2020-01-01
func GetBetweenDates(sdate, edate string) []string {
d := []string{}
if sdate == edate {
d = append(d, sdate)
return d
}
timeFormatTpl := "2006-01-02 15:04:05"
if len(timeFormatTpl) != len(sdate) {
timeFormatTpl = timeFormatTpl[0:len(sdate)]
}
date, err := time.Parse(timeFormatTpl, sdate)
if err != nil {
// 时间解析,异常
return d
}
date2, err := time.Parse(timeFormatTpl, edate)
if err != nil {
// 时间解析,异常
return d
}
if date2.Before(date) {
// 如果结束时间小于开始时间,异常
return d
}
// 输出日期格式固定
timeFormatTpl = "2006-01-02"
date2Str := date2.Format(timeFormatTpl)
d = append(d, date.Format(timeFormatTpl))
for {
date = date.AddDate(0, 0, 1)
dateStr := date.Format(timeFormatTpl)
d = append(d, dateStr)
if dateStr == date2Str {
break
}
}
return d
}
//时间段24小时
func GetHourList(sdate, edate string) []string {
dates := GetBetweenDates(sdate, edate)
hour := []string{"00:00:00", "01:00:00", "02:00:00", "03:00:00", "04:00:00", "05:00:00", "06:00:00", "07:00:00", "08:00:00", "09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00", "23:00:00"}
h := make([]string, 0)
for _, val := range dates {
for _, va2 := range hour {
h = append(h, val+" "+va2)
}
}
return h
}