Can't I use variables for time calculations in golang?

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

Can't I use variables for time calculations in golang?

问题

我正在尝试计算10分钟前的时间。
为什么我不能使用变量进行这个计算(可用于for循环)。
请看以下代码:

package main

import (
	"fmt"
	"time"
)

func main() {

	// 当前时间
	fmt.Println(time.Now())

	// 50分钟前的时间 - 正常工作
	diff := (60 - 10) * time.Minute
	newTime := time.Now().Add(-diff)
	fmt.Println(newTime)

	// 50分钟前的时间 - 不工作!
	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)

谢谢!

英文:

I'm trying to calculate the time 10 minutes ago.
Why can't I do this calculation with variables (usable for a for loop).
See -

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)
}

Why diff = (60 - i) * time.Minute doesn't work?
This is the error I'm getting -

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

For Go Playground: https://play.golang.org/p/TJ03K0ULg2

Thanks a lot!

答案1

得分: 8

根据错误提示,你的类型不匹配。将整数结果转换为 time.Duration 类型:

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

Like the error says, you have mismatched types. Convert the integer result to a time.Duration:

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

答案2

得分: 1

time.Duration实际上是int64类型,所以如果你想使用变量来实现你想要的效果,只需将变量声明为time.Duration,像这样:

package main

import (
    "fmt"
    "time"
)

func main() {

    // 当前时间
    fmt.Println(time.Now())

    // 50分钟前的时间 - 正常工作
    diff := (60 - 10) * time.Minute
    newTime := time.Now().Add(-diff)
    fmt.Println(newTime)

    // 50分钟前的时间 - 不起作用!
    var i time.Duration
    diff = (60 - i) * time.Minute
    newTime = time.Now().Add(-diff)
    fmt.Println(newTime)
}

希望对你有帮助!

英文:

time.Duration actually is type int64,so if you want to use variable to make what you want,just declare the variable to time.Duration,like this:

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)
}

huangapple
  • 本文由 发表于 2016年4月13日 23:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/36603202.html
匿名

发表评论

匿名网友

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

确定