美文网首页
golang time包t.After的坑

golang time包t.After的坑

作者: 悟道人 | 来源:发表于2019-07-11 08:47 被阅读0次

代码如下

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判断上有点奇怪

相关文章

网友评论

      本文标题:golang time包t.After的坑

      本文链接:https://www.haomeiwen.com/subject/figlkctx.html