Search code examples
timegounix-timestamp

Get 3 years ago timestamp in golang?


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


Solution

  • 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