2025年3月14日 星期五 甲辰(龙)年 月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Go语言

go语言,根据开始日期和结束日期计算出时间段内所有日期

时间:02-04来源:作者:点击数:39

go语言,根据开始日期和结束日期计算出时间段内所有日期

  • // 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
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门