patterngoCritical
Subtracting time.Duration from time in Go
Viewed 0 times
durationtimefromsubtracting
Problem
I have a
I know subtracting is possible with
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 with
time.Sub() (which wants another time.Time), but that will result in a time.Duration and I need it the other way around.Solution
Try AddDate:
Produces:
Playground: http://play.golang.org/p/QChq02kisT
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 UTCPlayground: http://play.golang.org/p/QChq02kisT
Code Snippets
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 UTCContext
Stack Overflow Q#26285735, score: 188
Revisions (0)
No revisions yet.