时间日期处理

time

package main

import (
	"fmt"
	"time"
)

func main() {

	// 获取当前时间
	now := time.Now() // time.Time
	fmt.Println(now) // 2021-09-11 06:49:44.214802 +0800 CST m=+0.000060376

	// 获取指定时间的年月日时分秒等
	fmt.Printf("%d年%d月%d日%d时%d分%d秒\n", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) // month 是从1开始的,人性化

	// 时间日期格式化
	// 除了使用Sprintf方法,也可以使用日期时间包的format方法
	nowStr := now.Format("2006-01-02 15:01:05") // golang诞生的时间
	fmt.Println(nowStr)

	// 时间常量
	// 睡眠一秒钟,除了Second,还有 Hour、Minute、Millisecond、Microsecond、Nanosecond
	time.Sleep(time.Second)

	// Unix时间戳
	fmt.Println("Unix毫秒:", now.Unix())
	fmt.Println("Unix纳秒:", now.UnixNano())
}

最后更新于