Go time包使用

本文最后更新于:13 天前

1 time包使用

package main

import (
	"fmt"
	"time"
)

func main() {
	timeNow := time.Now()
	fmt.Println(timeNow)

	Year := timeNow.Year()
	Month := timeNow.Month()
	Day := timeNow.Day()
	Hour := timeNow.Hour()
	Minute := timeNow.Minute()
	Second := timeNow.Second()
	fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", Year, Month, Day, Hour, Minute, Second)

	/*
	   年:2006
	   月:01
	   日:02
	   时:03    12小时  15: 24小时
	   分:04
	   秒:05
	*/
	timeNow1 := time.Now()
	var str = timeNow1.Format("2006/01/02 03:04:05")
	var str1 = timeNow1.Format("2006/01/02 15:04:05")
	fmt.Println(str)  //2020/12/09 01:58:02
	fmt.Println(str1) //2020/12/09 13:58:02

}

2 格式化转换

package main

import (
	"fmt"
	"time"
)

func main() {
	//获取时间戳
	timeNow := time.Now()
	unixtime := timeNow.Unix()       //获取当前毫秒时间戳
	unixNatime := timeNow.UnixNano() //获取当前纳秒时间戳
	fmt.Println(unixtime, unixNatime)

	//时间戳转换成日期
	unixtime1 := 1607493629
	timeNow1 := time.Unix(int64(unixtime1), 0) //注意类型是int64
	var str1 = timeNow1.Format("2006-01-02 15:04:05")
	fmt.Println(str1)
	//日期字符串转换为时间戳
	var str2 = "2020-12-09 14:00:29"
	var tmp = "2006-01-02 15:04:05"
	timeNow2, _ := time.ParseInLocation(tmp, str2, time.Local)
	fmt.Println(timeNow2)
	fmt.Println(timeNow2.Unix())

}

3 time定义时间间隔的常量

time.Second //1秒
time.Millisecond/ //1毫秒

4 时间操作函数

Add
Sub
Equal
Before 
After

5 定时器

package main

import (
	"fmt"
	"time"
)
func main() {
	//定时器 每隔一秒钟
	ticker := time.NewTicker(time.Second)
	n := 5
	//ticker.C
	for t := range ticker.C {
		n--
		fmt.Println(t)
		if n == 0 {
			ticker.Stop()
			break
		}
	}
//第二种方法
	for {
		time.sleep(time.Second)
		fmt.Println("...")
	}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!