获取两个日期之间的日期列表

// GetBetweenDates 根据开始日期和结束日期计算出时间段内所有日期
// 参数为日期格式,如:2020-01-01
func GetBetweenDates(sdate, edate string) []string {
    d := []string{}
    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
}

相关文章:

  • 2021-10-14
  • 2021-09-03
  • 2022-01-18
  • 2021-05-20
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2021-06-30
猜你喜欢
  • 2022-01-29
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
相关资源
相似解决方案