我正在计算 golang 中的日期差异,我已经编写了代码并且它执行得很好但是当我以分钟为单位计算时间差异时,将其转换为整数并在 if 条件下进行比较。我正在尝试的代码根据以下条件,它不应打印“diffinmin is greater P”,但它正在打印。我哪里做错了?package mainimport ( "fmt" "time" "strconv")func main() { //fetching current time currentTime := time.Now() loc := currentTime.Location() //past time comes in as string pasttimestr := "2018-10-18 01:00" layout := "2006-01-02 15:04" //converting string to date pasttime, err := time.ParseInLocation(layout, pasttimestr, loc) if err != nil { fmt.Println(err) } fmt.Println("Past Time: ", pasttime) fmt.Println("Current Time: ", currentTime) //differnce between pastdate and current date diff := currentTime.Sub(pasttime) var diffinmin int = int(diff.Minutes()) fmt.Printf( "heloo",diffinmin ) fmt.Printf("time difference is %v or %v in minutes\n", diff, diff.Minutes()) var strconfigtime = "9000" var mininttimeconfig int if mininttimeconfig, err := strconv.Atoi(strconfigtime); err == nil { fmt.Printf("i=%d, type: %T\n", mininttimeconfig, mininttimeconfig) } if diffinmin > mininttimeconfig { fmt.Printf("diffinmin is greater" ) }}小提琴:https://play.golang.org/p/x6-RebYycpk
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
它是关于范围的,您在检查中使用的 mininttimeconfig 的值为 0。
if mininttimeconfig, err := strconv.Atoi(strconfigtime); err == nil {
// mininttimeconfig is a new variable scoped to this block
}
// here mininttimeconfig is 0 from declaration line
// var mininttimeconfig int
尝试将行更改为:
var mininttimeconfig int
mininttimeconfig, err = strconv.Atoi(strconfigtime);
if err == nil {
// ...
或者:
mininttimeconfig, err := strconv.Atoi(strconfigtime);
if err == nil {
// ...
注意通常使用 error 就像 if err != nil {...}
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消