Subtracting time.Duration from time in Go

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

提交回复
热议问题