如果golang中的条件出了问题

时间:2018-10-17 20:43:27

标签: date datetime go

我正在用golang计算日期差,我已经写了代码并且执行得很好,但是当我以分钟为单位计算时间差时,将其转换为整数并在if条件下进行比较。

正在尝试的代码

根据以下条件,它不应打印“ diffinmin更大 P”,但它正在打印。我在哪里做错了?

package main

import (
    "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 个答案:

答案 0 :(得分: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 { 
       // ...

请注意,通常使用错误,例如err!= nil {...}