我不能在golang中使用变量进行时间计算吗?

时间:2016-04-13 15:34:49

标签: go time calc

我试图计算10分钟前的时间。 为什么我不能用变量进行计算(可用于for循环)。 见 -

package main

import (
    "fmt"
    "time"
)

func main() {

    // the time now
    fmt.Println(time.Now())

    // the time 50 minutes ago - WORKS
    diff := (60 - 10) * time.Minute
    newTime := time.Now().Add(-diff)
    fmt.Println(newTime)

    // the time 50 minutes ago - DOESN'T WORKS!
    i := 10
    diff = (60 - i) * time.Minute
    newTime = time.Now().Add(-diff)
    fmt.Println(newTime)
}

为什么diff = (60 - i) * time.Minute不起作用? 这是我得到的错误 -

prog.go:20: invalid operation: (60 - i) * time.Minute (mismatched types int and time.Duration)

对于Go Playground:https://play.golang.org/p/TJ03K0ULg2

非常感谢!

2 个答案:

答案 0 :(得分:5)

如错误所示,您的类型不匹配。将整数结果转换为time.Duration

diff = time.Duration(60-i) * time.Minute

答案 1 :(得分:1)

time.Duration实际上是int64类型,因此如果您想使用变量来制作您想要的内容,只需将变量声明为time.Duration,如下所示:

package main

import (
    "fmt"
    "time"
)

func main() {

    // the time now
    fmt.Println(time.Now())

    // the time 50 minutes ago - WORKS
    diff := (60 - 10) * time.Minute
    newTime := time.Now().Add(-diff)
    fmt.Println(newTime)

    // the time 50 minutes ago - DOESN'T WORKS!
    var i time.Duration
    diff = (60 - i) * time.Minute
    newTime = time.Now().Add(-diff)
    fmt.Println(newTime)
}