Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 472
roger Avatar asked Dec 07 '15 08:12

roger


2 Answers

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
like image 73
icza Avatar answered Oct 17 '22 01:10

icza


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

like image 42
Eds_k Avatar answered Oct 17 '22 02:10

Eds_k