Get 3 years ago timestamp in golang?

Maybe you can do this

package main

import (
    "fmt"
    "time"
)

func timeShift(now time.Time, timeType string, shift int) time.Time {
    var shiftTime time.Time
    switch timeType {
    case "year":
        shiftTime = now.AddDate(shift, 0, 0)
    case "month":
        shiftTime = now.AddDate(0, shift, 0)
    case "day":
        shiftTime = now.AddDate(0, 0, shift)
    case "hour":
        shiftTime = now.Add(time.Hour * time.Duration(shift))
    case "minute":
        shiftTime = now.Add(time.Minute * time.Duration(shift))
    case "second":
        shiftTime = now.Add(time.Second * time.Duration(shift))
    default:
        shiftTime = now
    }
    return shiftTime
}

func main(){
    d := time.Now().UTC()
    fmt.Println(timeShift(d, "month", 1))
    fmt.Println(timeShift(d, "day", -1))
    fmt.Println(timeShift(d, "hour", -1))
    fmt.Println(timeShift(d, "minute", -1))
    fmt.Println(timeShift(d, "second", -1))
}


Simply use the Time.AddDate() method where you can specify the time to add in years, months and days, all of which can also be negative if you want to go back in time:

AddDate() method declaration:

func (t Time) AddDate(years int, months int, days int) Time

Example:

t := time.Now()
fmt.Println(t)
t2 := t.AddDate(-3, 0, 0)
fmt.Println(t2)

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2006-11-10 23:00:00 +0000 UTC