17

I want to get the time unix time stamp 3 years ago, I use this now:

time.Now().Unix(() - 3 * 3600 * 24 * 365

This is not that accurate anyway (because year may have 366 days).

icza
  • 389,944
  • 63
  • 907
  • 827
roger
  • 9,063
  • 20
  • 72
  • 119

2 Answers2

46

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
icza
  • 389,944
  • 63
  • 907
  • 827
2

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))
}

Eds_k
  • 944
  • 10
  • 12
  • So you're saying, to adjust the "now" by a "shift" number of years: `now.AddDate(shift, 0, 0)` The current time can be adjusted to @roger's three years previous with your function using the following: `timeShift(time.Now(), year, -3)` – Tom Anderson Aug 28 '20 at 07:57