time包使用

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
posted @ 2022-09-02 14:55  sunnybowen  阅读(17)  评论(0编辑  收藏  举报