英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论