go 的时间操作
package main
import (
"fmt"
"time"
)
func testTime() {
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.Printf("时间字符串%05d-%02d-%02d %02d:%02d:%02d\n ", year, month, day, hour, minute, second)
fmt.Printf("类型%T,%T,%T %T,%T,%T\n ", year, month, day, hour, minute, second)
// 上面的%05d表示填充符号,不足5位用0填充,满足了就不管了了
timestamp := now.Unix()
fmt.Printf("timestamp is:%d\n", timestamp)
}
// # 时间戳,从1970年到现在的时间的秒数,时间戳数字转化为时间格式
func testTimestamp(timestamp int64) {
timeObj := time.Unix(timestamp, 0)
year := timeObj.Year()
month := timeObj.Month()
day := timeObj.Day()
hour := timeObj.Hour()
minute := timeObj.Minute()
second := timeObj.Second()
fmt.Printf("current timestamp :%d\n", timestamp)
fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d \n ", year, month, day, hour, minute, second)
}
func processTask() {
fmt.Printf("do task\n")
}
// 定时器
func testTicker() {
ticker := time.Tick(5 * time.Second) //每1秒,会把当前时间放入定时器管道里面
for i := range ticker {
fmt.Printf("这是i: %v\n", i)
processTask()
}
}
func testConst() {
fmt.Printf("nano second :%d\n", time.Nanosecond) // 纳秒
fmt.Printf("micro second :%d\n", time.Microsecond) // 微秒
fmt.Printf("milli second :%d\n", time.Millisecond) // 毫秒
fmt.Printf("second :%d\n", time.Second) // 秒
}
func testFormat() {
now := time.Now()
timeStr := now.Format("2006-01-02 15:04:05") // 用format格式化时间,年月日必须是2016年,1月2日,go语言诞生的时间,以这个2006-01-02 15:04:05时间作为模板
fmt.Printf("01>>time :%s\n", timeStr)
timeStr = now.Format("2006-1-2 15:04:05") // 用format格式化时间,年月日必须是2016年,1月2日,go语言诞生的时间
fmt.Printf("02>>time :%s\n", timeStr)
timeStr = now.Format("2006/01/02 15:04:05") // 用format格式化时间,年月日必须是2016年,1月2日,go语言诞生的时间
fmt.Printf("03>>time :%s\n", timeStr)
timeStr = now.Format("01/02/2006 15:04:05") // 用format格式化时间,年月日必须是2016年,1月2日,go语言诞生的时间
fmt.Printf("04>>time :%s\n", timeStr)
timeStr = now.Format("01/02/2006 3:04:05") // 用format格式化时间,下午3点,12小时的格式
fmt.Printf("05>>time :%s\n", timeStr)
}
func testFormat2() {
now := time.Now()
timeStr := fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d \n ",
now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
fmt.Printf("time :%s\n", timeStr)
}
func testCost() {
start := time.Now().UnixNano() // 纳秒
for i := 0; i < 10; i++ {
time.Sleep(time.Millisecond)
}
end := time.Now().UnixNano()
cost := (end - start) / 1000
fmt.Printf("code cost:%d us\n", cost) //code cost:10000 us 大概10毫秒左右
}
func main() {
//testTime()
//timestamp := time.Now().Unix()
//testTimestamp(timestamp)
//testTicker() //定时器
//testConst()
testFormat()
testFormat2()
testCost()
}
输出:
01>>time :2022-03-12 18:29:36
02>>time :2022-3-12 18:29:36
03>>time :2022/03/12 18:29:36
04>>time :03/12/2022 18:29:36
05>>time :03/12/2022 6:29:36
time :2022-03-12 18:29:36
code cost:10000 us