> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/programming-language/golang/chang-yong-api/shi-jian-ri-qi-chu-li.md).

# 时间日期处理

## `time`包

```go
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())
}
```
