1、获取字符串时间
//获取年、月、日、时、分、秒
getYear := time.Now().Year() //获取年
getMonth := time.Now().Format("01") //获取月
getDay := time.Now().Day() 获取日
或者
getYear := time.Now().Format("2006") //获取年
getMonth := time.Now().Format("01") //获取月
getDay := time.Now().Format("02") 获取日
hour := time.Now().Format("15")
min := time.Now().Format("04")
second := time.Now().Format("05")
fmt.Println("year:", year, "month:", month, "day:", day)
fmt.Println("hour:", hour, "min:", min, "second:", second)
//输出:year: 2021 month: 04 day: 23
// hour: 15 min: 16 second: 53
//获取日期各种格式
todaystr1 := time.Now().Format("2006-01-02 15:04:05")
fmt.Println("todaystr1:", todaystr1)
todaystr2 := time.Now().Format("2006/01/02 15:04:05")
fmt.Println("todaystr2:", todaystr2)
todaystr3 := time.Now().Format("2006-01-02")
fmt.Println("todaystr3:", todaystr3)
todaystr4 := time.Now().Format("15:04:05")
fmt.Println("todaystr4:", todaystr4)
//输出:todaystr1: 2021-04-23 15:32:38
todaystr2: 2021/04/23 15:32:38
todaystr3: 2021-04-23
todaystr4: 15:32:38
2、获取时间戳
//时间转换的模板,golang里面只能是 "2006-01-02 15:04:05" (go的诞生时间)
timeTemplate1 := "2006-01-02 15:04:05" //常规类型
timeTemplate2 := "2006/01/02 15:04:05" //其他类型
timeTemplate3 := "2006-01-02" //其他类型
timeTemplate4 := "15:04:05" //其他类型
//当前日期(年-月-日)的时间戳
todaystr := time.Now().Format("2006-01-02")
//使用parseInLocation将字符串格式化返回本地时区时间
todayint, _ := time.ParseInLocation(timeTemplate3, todaystr, time.Local)
fmt.Println("日期:", todaystr, "的时间戳是:", todayint.Unix())
//输出:日期: 2021-04-23 的时间戳是: 1619107200
//当前时间(年-月-日 时:分:秒)的时间戳
todaystr := time.Now().Format("2006-01-02 15:04:05")
todayint, _ := time.ParseInLocation(timeTemplate1 , todaystr, time.Local) /
fmt.Println("日期:", todaystr, "的时间戳是:", todayint.Unix())
//输出:日期: 2021-04-23 15:44:19 的时间戳是: 1619163859
注:获取前一天日期:
currentTime := time.Now()
oldTime1 := currentTime.AddDate(0, 0, -1) //前5天就写-5。
先写到这儿,以后用到再补充。