How to do date/time comparison

后端 未结 5 1910
一向
一向 2020-12-23 15:25

Is there any options in doing date comparison in Go? I have to sort data based on date and time - independently. So I might allow an object that occurs within a range of dat

5条回答
  •  忘掉有多难
    2020-12-23 16:17

    For comparison between two times use time.Sub()

    // utc life
    loc, _ := time.LoadLocation("UTC")
    
    // setup a start and end time
    createdAt := time.Now().In(loc).Add(1 * time.Hour)
    expiresAt := time.Now().In(loc).Add(4 * time.Hour)
    
    // get the diff
    diff := expiresAt.Sub(createdAt)
    fmt.Printf("Lifespan is %+v", diff)
    

    The program outputs:

    Lifespan is 3h0m0s
    

    http://play.golang.org/p/bbxeTtd4L6

提交回复
热议问题