3年前golang中的时间戳?

时间:2015-12-07 08:30:54

标签: time go unix-timestamp

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

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

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

2 个答案:

答案 0 :(得分:23)

只需使用Time.AddDate()方法,您可以指定以年,月和日为单位添加的时间,如果您想要及时返回,所有这些方法也可能为负数:

AddDate()方法声明:

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

示例:

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

输出(在Go Playground上尝试):

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

答案 1 :(得分:0)

也许你可以做到

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