我有一个time.Time从中获得的值time.Now(),我想再获得一次,也就是 1 个月前。
time.Time
time.Now()
我知道可以使用time.Sub()(需要另一个time.Time)进行减法,但这会导致 a ,time.Duration而我需要反过来。
time.Sub()
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
为了回应 Thomas Browne 的评论,因为lnmx 的答案仅适用于减去日期,这里是对他的代码的修改,用于从 time.Time 类型中减去时间。
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) }
now: 2009-11-10 23:00:00 +0000 UTC 10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
更不用说,您还可以根据需要使用time.Hour或time.Second代替time.Minute。
time.Hour
time.Second
time.Minute