从Go中减去time.Duration
我有一个时间time.Now()时间价值,我想要得到另一个正好是1个月前的时间。 
 我知道减法是可能的time.Sub() (这需要另一个time.Time ),但是这将导致time.Duration ,我需要它相反。 
尝试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) } 
生产:
 now: 2009-11-10 23:00:00 +0000 UTC then: 2009-10-10 23:00:00 +0000 UTC 
游乐场: http : //play.golang.org/p/QChq02kisT
为了回应Thomas Browne的评论,因为lnmx的答案只适用于减去date,下面是他的代码的修改,用于从时间减去时间。时间types。
 package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println("now:", now) then := now.Add(-10 * time.Minute) fmt.Println("10 minutes ago:", then) } 
生产:
 now: 2009-11-10 23:00:00 +0000 UTC 10 minutes ago: 2009-11-10 22:50:00 +0000 UTC 
 你可以否定一个时间time.Duration 
 then := now.Add(- dur) 
 你甚至可以比较一下time.Duration和0 : 
 if dur > 0 { dur = - dur } then := now.Add(dur)