HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Subtracting time.Duration from time in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
durationtimefromsubtracting

Problem

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 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:

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 UTC


Playground: 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 UTC

Context

Stack Overflow Q#26285735, score: 188

Revisions (0)

No revisions yet.