donglun7151 2018-01-21 23:48
浏览 26
已采纳

在Golang的Time包中无法迭代到年底结束的几天

I'm trying to iterate through days between 2 dates. One date is time.Parse("2006-01-02", "2017-08-24") another is time.Now() but my loop seems to be stopping at the turn of the year and I can't figure out why.

func IsToday(date time.Time) bool {
    today := time.Now()
    return date.Year() == today.Year() &&
           date.Month() == today.Month() &&
           date.Day() == date.Day()
}

t1, _ := time.Parse("2006-01-02", "2017-08-24")

for curr := t1; !IsToday(curr); curr = curr.AddDate(0,0,1) {
        fmt.Println(curr)
}

The loop prints out:

2017-08-24 00:00:00 +0000 UTC
2017-08-25 00:00:00 +0000 UTC
2017-08-26 00:00:00 +0000 UTC
2017-08-27 00:00:00 +0000 UTC
2017-08-28 00:00:00 +0000 UTC
2017-08-29 00:00:00 +0000 UTC
2017-08-30 00:00:00 +0000 UTC
2017-08-31 00:00:00 +0000 UTC
2017-09-01 00:00:00 +0000 UTC
2017-09-02 00:00:00 +0000 UTC
...
2017-12-18 00:00:00 +0000 UTC
2017-12-19 00:00:00 +0000 UTC
2017-12-20 00:00:00 +0000 UTC
2017-12-21 00:00:00 +0000 UTC
2017-12-22 00:00:00 +0000 UTC
2017-12-23 00:00:00 +0000 UTC
2017-12-24 00:00:00 +0000 UTC
2017-12-25 00:00:00 +0000 UTC
2017-12-26 00:00:00 +0000 UTC
2017-12-27 00:00:00 +0000 UTC
2017-12-28 00:00:00 +0000 UTC
2017-12-29 00:00:00 +0000 UTC
2017-12-30 00:00:00 +0000 UTC
2017-12-31 00:00:00 +0000 UTC

Notice how it does not iterate till today's date. Testing the AddDate individually as time.Parse("2006-01-02", "2017-12-31").AddDate(0,0,1) does result in 2018-01-01.

  • 写回答

1条回答 默认 最新

  • douhe1864 2018-01-22 00:32
    关注

    Calculate tomorrow's date and iterate while curr is before that date:

    now := time.Now()
    tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).AddDate(0, 0, 1)
    for curr := t1; curr.Before(tomorrow); curr = curr.AddDate(0, 0, 1) {
        fmt.Println(curr)
    }
    

    Iterating while !IsToday(curr) (with typo corrected) is fragile because it will loop forever if the starting time is after the current time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!