步骤说明

如果你是PHP开发,可以这样记

PHP 中的 Y-m-d H:i:s 等于 Golang 中的 2006-01-02 15:04:05

当前时间戳

时间戳(秒):seconds := time.Now().Unix()
时间戳(纳秒):time.Now().UnixNano()
时间戳(毫秒):time.Now().UnixNano() / 1e6
时间戳(纳秒转换为秒):time.Now().UnixNano() / 1e9

当前时间

currentTime := time.Now()
fmt.Println(currentTime)
// 输出:2021-05-24 22:17:02.678787 +0800 CST m=+0.000129143

currentTime := time.Now().Format("2006-01-02 15:04:05")
// 输出:2021-05-24 22:17:02

时间戳格式化

currentTime := time.Now().Format("2006-01-02 15:04:05")
timestamp, _ := time.ParseInLocation("2006-01-02 15:04:05" , currentTime, time.Local)
// 输出:1622700677

几天前 & 几天后

3天前
currentTime := time.Now()
oTime := currentTime.AddDate(0, 0, -3)

// 3天后
currentTime := time.Now()
expirationTime := currentTime.AddDate(0, 0, 3).Sub(currentTime)

一分钟前

:
t := currentTime.Add(time.Minute * -1)
lastM := t.Unix() - int64(now.Second()) // 上一分钟时间-上一分钟秒数

year := time.Now().Year()
year := time.Now().Format("2006")

month := time.Now().Month()
month = time.Now().Format("01")
month := time.Now().Month().String()

day := time.Now().Day()
day := time.Now().Format("02")

时分秒

hour := time.Now().Format("15")
min := time.Now().Format("04")
second := time.Now().Format("05")

今日日期

time.Now().Format("20060102")
"20210520"

获取今天指定时间戳

// 今日9点时间戳
timeUnix := time.Date(t.Year(), t.Month(), t.Day(), 9, 0, 0, 0, t.Location()).Unix()

时间戳转字符串&字符串转时间戳

t :=time.Now().Unix()

timeStr= "2021-06-07 16:29:20"`
`formatTime, err := time.Parse("2006-01-02 15:04:05", timeStr)

参考文献

Golang获取年月日时间字符串和时间戳