How to do date/time comparison

后端 未结 5 1892
一向
一向 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:26

    Use the time package to work with time information in Go.

    Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

    Play example:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func inTimeSpan(start, end, check time.Time) bool {
        return check.After(start) && check.Before(end)
    }
    
    func main() {
        start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
        end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
    
        in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
        out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
    
        if inTimeSpan(start, end, in) {
            fmt.Println(in, "is between", start, "and", end, ".")
        }
    
        if !inTimeSpan(start, end, out) {
            fmt.Println(out, "is not between", start, "and", end, ".")
        }
    }
    

提交回复
热议问题