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

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。

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

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

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010244957

加油吧女码农

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值