golang time包t.After的坑

代码如下

package main

import (
    "fmt"
    "time"
)

func main() {
    const FORMAT = "2006-01-02 15:04:05"
    t := time.Now()
    fmt.Println(t.Location(), t.Format(FORMAT))
    time.Sleep(time.Second * 10)
    newTime := t.Add(time.Hour * 5) //之前时间加上5小时
    currentTime := time.Now()       //当前时间
    if newTime.After(time.Now()) {
        fmt.Println(newTime.Format(FORMAT), " 大于 ", currentTime.Format(FORMAT))
    } else {
        fmt.Println(newTime.Format(FORMAT), " 小于 ", currentTime.Format(FORMAT))
    }
}

执行到time.Sleep(time.Second * 10)时,将电脑时间改为1天后,执行结果如下

Local 2020-03-26 14:31:36
2020-03-26 19:31:36  大于  2020-03-27 14:31:45

如果t := time.Now().Local() 加上local就没有问题

package main

import (
    "fmt"
    "time"
)

func main() {
    const FORMAT = "2006-01-02 15:04:05"
    t := time.Now().Local() //加上local
    fmt.Println(t.Location(), t.Format(FORMAT))
    time.Sleep(time.Second * 10)
    newTime := t.Add(time.Hour * 5) //之前时间加上5小时
    currentTime := time.Now()       //当前时间
    if newTime.After(time.Now()) {
        fmt.Println(newTime.Format(FORMAT), " 大于 ", currentTime.Format(FORMAT))
    } else {
        fmt.Println(newTime.Format(FORMAT), " 小于 ", currentTime.Format(FORMAT))
    }
}

输出了正常结果

Local 2020-03-26 14:32:20
2020-03-26 19:32:20  小于  2020-03-27 14:32:29

time.After判断上有点奇怪

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容