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

标签 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)

围棋 Playground :https://play.golang.org/p/TJ03K0ULg2

非常感谢!

最佳答案

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

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

关于go - 我不能在golang中使用变量进行时间计算吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603202/

相关文章:

arrays - 如何在 Go 中创建自定义类型元素的自定义类型数组?

json - Martini 中的 JSON 编码错误

list - 为什么 golang list/ring 的 Element 和 Ring 结构?

ruby - 在 Ruby 中表示时差

创建将当前时间打印到命令行的 pthread

CSS calc() 与多个单位相乘

go - Aerospike 3.6.4 列表插入操作给出 'Server error'

qt - 如何让 Qt 将 QVariant 视为 UTC 时间戳?

Libreoffice : Referencing cells in another worksheet via FIND(), LOOKUP(),还是 EXACT()?

javascript - 如何使 JS/HTML5 计算器的结果变为多行?