ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

time包使用

2022-09-02 15:00:20  阅读:149  来源: 互联网

标签:07 fmt time 2022 使用 Println now


1、获取年月日

func timeDemo() {
	now := time.Now() //获取当前时间
	fmt.Printf("current time:%v\n", now)

	year := now.Year()
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	// 年月日时分秒
	fmt.Println(year, month, day, hour, minute, second)
}

out

current time:2022-06-30 17:32:01.9837588 +0800 CST m=+0.003915501
2022 June 30 17 32 1

2、获取时间戳

func demostampDemo() {
	now := time.Now()        //获取当前时间
	timestamp := now.Unix()  //秒级时间戳
	milli := now.UnixMilli() //毫秒级时间戳 Go1.17+
	micro := now.UnixMicro() //微妙时间戳GO1.17+
	nano := now.UnixNano()   //纳秒时间戳
	fmt.Println(timestamp, milli, micro, nano)
}

out

1656581851 1656581851094 1656581851094900 1656581851094900600

3、时间戳转时间

func unixDemo() {
	ret := time.Unix(1654570899, 0) //前面是s,后面是标志位,一般是0
	fmt.Println(ret)
	fmt.Println(ret.Year())
	fmt.Println(ret.Month())
}

out

2022-06-07 11:01:39 +0800 CST
2022
June

4、当前时间加减操作

func jiange() {
	fmt.Println(time.Second)
	//now+1h
	now := time.Now()
	//当前时间+24h
	fmt.Println(now.Add(24 * time.Hour))
	//当前时间加10分钟
	fmt.Println(now.Add(10 * time.Minute))
	//sub
	//equal
	//before after
}

out

1s
2022-07-05 17:50:36.8357548 +0800 CST m=+86400.004206301
2022-07-04 18:00:36.8357548 +0800 CST m=+600.004206301

5、时间格式转换

func formatDemo() {
	now := time.Now()
	fmt.Println(now.Format("2006-01-02"))
	fmt.Println(now.Format("2006/01/02 15:04:05"))
	fmt.Println(now.Format("2006/01/02 03:04:05 PM"))  //没有PM默认就是AM,03表示上午
	fmt.Println(now.Format("2006/01/02 03:04:05.000")) //
}

out

2022-07-05
2022/07/05 11:18:38
2022/07/05 11:18:38 AM
2022/07/05 11:18:38.597

6、解析时间格式

func timestamp() {
	timeObj, err := time.Parse("2006-01-02", "2022-06-07") // 给日期,解析成时间对象
	if err != nil {
		fmt.Printf("parse time failed err:%v\n", err)
		return
	}
	fmt.Println(timeObj)
	fmt.Println(timeObj.Unix())
}

out

2022-06-07 00:00:00 +0000 UTC
1654560000

标签:07,fmt,time,2022,使用,Println,now
来源: https://www.cnblogs.com/sunnybowen/p/16649905.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有