Subtracting time.Duration from time in Go

前端 未结 4 2213
遇见更好的自我
遇见更好的自我 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: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

提交回复
热议问题