duanshan3065 2019-01-10 15:49
浏览 59
已采纳

在time.Now()到达时进行循环

Is it possible in Golang to increment a date in a for loop by a given date variable till it reached the current date/ time.Now()

// Start date
t, _ := time.Parse(time.RFC3339, "2018-07-19T12:25:10.8584224+02:00")

// Current date
ct := time.Now()

for d := t; d.Day() == ct.Day(); d = d.AddDate(0, 0, 1) {
    // Print all days between start date and current date 
    fmt.Println(d)
}

I expect that variable d prints out all dates (with time etc.) till it reached the current date

  • 写回答

4条回答 默认 最新

  • doudouxuqh198138 2019-01-16 08:55
    关注

    according to godoc: https://golang.org/pkg/time/#Time.Day

    func (t Time) Day() int

    Day returns the day of the month specified by t.

    So comparing d.Day() and ct.Day() is not the right approaches. What if today is "2019-01-01",and you start time is "2018-12-23"?

    The right way to compare two time.Time is https://golang.org/pkg/time/#Time.After

    func (t Time) After(u Time) bool
    func (t Time) Before(u Time) bool
    

    After reports whether the time instant t is after u. Before reports whether the time instant t is before u.

    So @Alex Pliutau's solution is more in common use. But need more careful with today.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        t, _ := time.Parse(time.RFC3339, "2009-11-02T12:25:10.8584224+02:00")
    
        // truncate to 0:0:0
        t = t.Truncate(24 * time.Hour)
        fmt.Println("start time is:", t)
    
        // Current date truncate to 0:0:0
        ct := time.Now().Truncate(24 * time.Hour)
        fmt.Println("now is:", ct)
        fmt.Println("---------------")
    
        // for t.Before(ct) {  //if you don't want to print the date of today
        for !t.After(ct) {
            // Print all days between start date and current date
            fmt.Println(t.Format("2006-01-02 15:04:05"))
            t = t.AddDate(0, 0, 1)
        }
    }
    

    Output:

    start time is: 2009-11-02 02:00:00 +0200 +0200
    now is: 2009-11-10 00:00:00 +0000 UTC
    ---------------
    2009-11-02 02:00:00
    2009-11-03 02:00:00
    2009-11-04 02:00:00
    2009-11-05 02:00:00
    2009-11-06 02:00:00
    2009-11-07 02:00:00
    2009-11-08 02:00:00
    2009-11-09 02:00:00
    2009-11-10 02:00:00
    

    https://play.golang.org/p/iMr7M5W9K4N

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 想用octave解决这个数学问题
  • ¥15 Centos新建的临时ip无法上网,如何解决?
  • ¥15 海康威视如何实现客户端软件对设备语音请求的处理。
  • ¥15 支付宝h5参数如何实现跳转
  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)