3年前golang中的时间戳?

rog*_*ger 9 time go unix-timestamp

我想在3年前得到时间unix时间戳,我现在用它:

time.Now().Unix(() - 3 * 3600 * 24 * 365
Run Code Online (Sandbox Code Playgroud)

无论如何这都不准确(因为年份可能有366天).

icz*_*cza 25

只需使用Time.AddDate()您可以指定添加时间的方法,包括年,月和日,如果您想要追溯到时间,所有这些也可以是负数:

AddDate() 方法声明:

func (t Time) AddDate(years int, months int, days int) Time
Run Code Online (Sandbox Code Playgroud)

例:

t := time.Now()
fmt.Println(t)
t2 := t.AddDate(-3, 0, 0)
fmt.Println(t2)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上试试):

2009-11-10 23:00:00 +0000 UTC
2006-11-10 23:00:00 +0000 UTC
Run Code Online (Sandbox Code Playgroud)