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

时间:2025-03-04 07:07:47

1、获取字符串时间

//获取年、月、日、时、分、秒
getYear := ().Year() //获取年
getMonth := ().Format("01") //获取月
getDay := ().Day() 获取日
或者
getYear := ().Format("2006") //获取年
getMonth := ().Format("01") //获取月
getDay  := ().Format("02") 获取日
hour := ().Format("15")
min := ().Format("04")
second := ().Format("05")

("year:", year, "month:", month, "day:", day) 
("hour:", hour, "min:", min, "second:", second)
//输出:year: 2021 month: 04 day: 23
//      hour: 15 min: 16 second: 53
//获取日期各种格式
todaystr1 := ().Format("2006-01-02 15:04:05")
("todaystr1:", todaystr1)

todaystr2 := ().Format("2006/01/02 15:04:05")
("todaystr2:", todaystr2)

todaystr3 := ().Format("2006-01-02")
("todaystr3:", todaystr3)

todaystr4 := ().Format("15:04:05")
("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 := ().Format("2006-01-02")
//使用parseInLocation将字符串格式化返回本地时区时间
todayint, _ := (timeTemplate3, todaystr, ) 
("日期:", todaystr, "的时间戳是:", ()) 
//输出:日期: 2021-04-23 的时间戳是: 1619107200

//当前时间(年-月-日 时:分:秒)的时间戳
todaystr := ().Format("2006-01-02 15:04:05")
todayint, _ := (timeTemplate1 , todaystr, ) /
("日期:", todaystr, "的时间戳是:", ())
//输出:日期: 2021-04-23 15:44:19 的时间戳是: 1619163859

注:获取前一天日期:

currentTime := ()

oldTime1 := (0, 0, -1)  //前5天就写-5。

先写到这儿,以后用到再补充。

参考文章:golang的time包:时间字符串和时间戳的相互转换

                 Golang如何获取当前年份月份日