Subtracting time.Duration from time in Go

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

提交回复
热议问题