我有一个time.Time价值time.Now(),我希望得到另一个时间,正好是1个月前.
我知道减法是可能的time.Sub()(它想要另一个time.Time),但这将导致a time.Duration,我需要它反过来.
小智 121
回应Thomas Browne的评论,因为lnmx的答案仅适用于减去日期,所以这里修改了他的代码,用于从时间中减去时间.时间类型.
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)
}
Run Code Online (Sandbox Code Playgroud)
生产:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Run Code Online (Sandbox Code Playgroud)
更不用说,您也可以根据自己的需要使用time.Hour或time.Second代替time.Minute.
游乐场:https://play.golang.org/p/DzzH4SA3izp
lnm*_*nmx 113
试试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)
}
Run Code Online (Sandbox Code Playgroud)
生产:
now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC
Run Code Online (Sandbox Code Playgroud)
游乐场:http://play.golang.org/p/QChq02kisT
doc*_*hat 40
你可以否定一个time.Duration:
then := now.Add(- dur)
Run Code Online (Sandbox Code Playgroud)
你甚至可以比较time.Duration反对0:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
Run Code Online (Sandbox Code Playgroud)
您可以在http://play.golang.org/p/ml7svlL4eW上看到一个有效的例子
根据手册,它time.ParseDuration会很乐意接受负持续时间。换句话说,没有必要否定持续时间,您可以首先获得准确的持续时间。
例如,当您需要减去一个半小时时,您可以这样做:
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)
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/63p-T9uFcZo