Subtracting time.Duration from time in Go

前端 未结 4 2136
遇见更好的自我
遇见更好的自我 2021-01-31 06:45

I have a time.Time value obtained from time.Now() and I want to get another time which is exactly 1 month ago.

I know subtracting is possible

相关标签:
4条回答
  • 2021-01-31 07:14

    Try AddDate:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        now := time.Now()
    
        fmt.Println("now:", now)
    
        then := now.AddDate(0, -1, 0)
    
        fmt.Println("then:", then)
    }
    

    Produces:

    now: 2009-11-10 23:00:00 +0000 UTC
    then: 2009-10-10 23:00:00 +0000 UTC
    

    Playground: http://play.golang.org/p/QChq02kisT

    0 讨论(0)
  • 2021-01-31 07:18

    You can negate a time.Duration:

    then := now.Add(- dur)
    

    You can even compare a time.Duration against 0:

    if dur > 0 {
        dur = - dur
    }
    
    then := now.Add(dur)
    

    You can see a working example at http://play.golang.org/p/ml7svlL4eW

    0 讨论(0)
  • 2021-01-31 07:32

    There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

    E.g. when you need to substract an hour and a half, you can do that like so:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        now := time.Now()
    
        fmt.Println("now:", now)
    
        duration, _ := time.ParseDuration("-1.5h")
    
        then := now.Add(duration)
    
        fmt.Println("then:", then)
    }
    

    https://play.golang.org/p/63p-T9uFcZo

    0 讨论(0)
  • 2021-01-31 07:36

    In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        now := time.Now()
    
        fmt.Println("now:", now)
    
        count := 10
        then := now.Add(time.Duration(-count) * time.Minute)
        // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
        // then := now.Add(-10 * time.Minute)
        fmt.Println("10 minutes ago:", then)
    }
    

    Produces:

    now: 2009-11-10 23:00:00 +0000 UTC
    10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
    

    Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

    Playground: https://play.golang.org/p/DzzH4SA3izp

    0 讨论(0)
提交回复
热议问题