在 golang 中获取 3 年前的时间戳?
Get 3 years ago timestamp in golang?
我想获取3年前的time unix时间戳,我现在用这个:
time.Now().Unix(() - 3 * 3600 * 24 * 365
无论如何这都不太准确(因为一年可能有 366 天)。
直接用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
也许你可以做到这一点
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))
}
我想获取3年前的time unix时间戳,我现在用这个:
time.Now().Unix(() - 3 * 3600 * 24 * 365
无论如何这都不太准确(因为一年可能有 366 天)。
直接用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
也许你可以做到这一点
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))
}