douzhangkui2467 2018-10-17 20:43
浏览 38
已采纳

如果golang中的条件出了问题

I'm calculating date difference in golang, I have written code and it is executing fine but when i take the difference of time in minutes, convert the same to integer and comparing in if condition.

code which im trying

as per the below condition, it should not print "diffinmin is greater P" but it is printing. Where im doing wrong?

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
", diff, diff.Minutes())
    var strconfigtime = "9000"
    var mininttimeconfig int
    if mininttimeconfig, err := strconv.Atoi(strconfigtime); err == nil {
    fmt.Printf("i=%d, type: %T
", mininttimeconfig, mininttimeconfig)
     }

    if diffinmin  >  mininttimeconfig {
    fmt.Printf("diffinmin is greater" )
    }

}

fiddle: https://play.golang.org/p/x6-RebYycpk

  • 写回答

1条回答 默认 最新

  • dsn46282 2018-10-17 21:00
    关注

    It is about scoping, the mininttimeconfig you are using in check has the value of 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
    

    Try changing the lines as:

        var mininttimeconfig int
        mininttimeconfig, err = strconv.Atoi(strconfigtime);
        if err == nil { 
           // ...
    

    Or:

        mininttimeconfig, err := strconv.Atoi(strconfigtime);
        if err == nil { 
           // ...
    

    Note generally error is used like if err != nil {...}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧