time.Unix(t, offset) gives same time?

huangapple go评论77阅读模式
英文:

time.Unix(t, offset) gives same time?

问题

尝试使用以下Go代码获取连续的时间戳:

package main

import "fmt"
import "time"

func main() {
    ts := int64(1500000000)  // 起始时间戳
    for i := int64(0); i<1e6; i = i + 1000 { // 逐渐增加1e3
        t := time.Unix(ts, i)  // 获取起始时间戳加上i的时间
        fmt.Printf("%d %02d:%02d\n", ts+i, t.Hour(), t.Minute())
    }
}

输出结果如下:

....
1500995000 04:40
1500996000 04:40
1500997000 04:40
1500998000 04:40
1500999000 04:40

请问,这里有什么问题?为什么小时和分钟不变?(都是04:40)

go version go1.15.6 linux/amd64

英文:

Trying to obtain successive timestamps with below Go code

package main

import &quot;fmt&quot;
import &quot;time&quot;

func main () {
    ts := int64(1500000000)  // start
    for i := int64(0); i&lt;1e6; i = i + 1000 { // successively add 1e3
            t := time.Unix(ts, i)  // Get start + i
            fmt.Printf(&quot;%d %02d:%02d\n&quot;, ts+i, t.Hour(), t.Minute())
    }
}

, output remains like

....
1500995000 04:40
1500996000 04:40
1500997000 04:40
1500998000 04:40
1500999000 04:40

Please, what is the problem here ? Why the hour:minute doesn't vary ? (04:40)

go version go1.15.6 linux/amd64

答案1

得分: 3

你正在更改纳秒并打印分钟...

func Unix(sec int64, nsec int64) Time

请查看这个链接:
https://play.golang.org/p/_Ywn9S5Khch

package main

import "fmt"
import "time"

func main() {
    ts := int64(1500000000)  // 开始时间
    for i := int64(0); i<1e6; i = i + 1000 { // 逐渐增加1e3
            t := time.Unix(ts, i)  // 获取开始时间 + i
            fmt.Printf("%d %02d:%02d ---- %2d\n", ts+i, t.Hour(), t.Minute(), t.UnixNano())
    }
}
英文:

You are changing the nanoseconds and printing minutes...

https://pkg.go.dev/time@go1.16.7#Unix

func Unix(sec int64, nsec int64) Time

Check this:
https://play.golang.org/p/_Ywn9S5Khch

package main

import &quot;fmt&quot;
import &quot;time&quot;

func main () {
    ts := int64(1500000000)  // start
    for i := int64(0); i&lt;1e6; i = i + 1000 { // successively add 1e3
            t := time.Unix(ts, i)  // Get start + i
            fmt.Printf(&quot;%d %02d:%02d ---- %2d\n&quot;, ts+i, t.Hour(), t.Minute(), t.UnixNano())
    }
}

huangapple
  • 本文由 发表于 2021年8月6日 23:31:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/68684162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定