潘逸安的博客

潘逸安

golang时间

在 Go 中获取当前时间有以下几种常用方式:

1. 获取当前时间(包含时区信息)

1
2
3
4
5
6
7
// 获取当前时间(本地时区)
now := time.Now()
fmt.Println(now) // 2023-10-01 15:30:45.123456 +08:00

// 获取当前 UTC 时间
utcNow := time.Now().UTC()
fmt.Println(utcNow) // 2023-10-01 07:30:45.123456 +0000 UTC

2. 获取时间的不同组成部分

1
2
3
4
5
6
7
8
9
10
now := time.Now()

year := now.Year() // 2023
month := now.Month() // October 或 10
day := now.Day() // 1
hour := now.Hour() // 15
minute := now.Minute() // 30
second := now.Second() // 45
nanosecond := now.Nanosecond() // 123456
weekday := now.Weekday() // Sunday

3. 格式化时间

1
2
3
4
5
6
7
8
now := time.Now()

// 格式化为字符串
fmt.Println(now.Format("2006-01-02 15:04:05")) // 2023-10-01 15:30:45
fmt.Println(now.Format("2006/01/02")) // 2023/10/01
fmt.Println(now.Format("15:04:05")) // 15:30:45
fmt.Println(now.Format(time.RFC3339)) // 2023-10-01T15:30:45+08:00
fmt.Println(now.Format(time.RFC1123)) // Sun, 01 Oct 2023 15:30:45 CST

4. 获取时间戳

1
2
3
4
5
6
7
8
9
10
11
12
13
now := time.Now()

// 秒级时间戳
timestamp := now.Unix() // 1696159845

// 毫秒级时间戳
milliTimestamp := now.UnixMilli() // 1696159845123

// 微秒级时间戳
microTimestamp := now.UnixMicro() // 1696159845123456

// 纳秒级时间戳
nanoTimestamp := now.UnixNano() // 1696159845123456789

5. 常用操作示例

1
2
3
4
5
6
7
8
9
10
11
12
13
// 获取今天开始时间(00:00:00)
today := time.Now().Truncate(24 * time.Hour)
fmt.Println(today) // 2023-10-01 00:00:00 +0800 CST

// 获取本月第一天
year, month, _ := time.Now().Date()
firstDayOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.Now().Location())

// 计算时间差
start := time.Now()
// ... 执行一些操作
duration := time.Since(start)
fmt.Printf("耗时: %v\n", duration)

6. 完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"time"
)

func main() {
// 获取当前时间
now := time.Now()

// 显示各种格式
fmt.Printf("当前时间: %v\n", now)
fmt.Printf("格式化: %s\n", now.Format("2006-01-02 15:04:05"))
fmt.Printf("时间戳(秒): %d\n", now.Unix())
fmt.Printf("时间戳(毫秒): %d\n", now.UnixMilli())

// 获取各部分
fmt.Printf("日期: %d年%d月%d日\n", now.Year(), now.Month(), now.Day())
fmt.Printf("时间: %02d:%02d:%02d\n", now.Hour(), now.Minute(), now.Second())
}

重要提示

  • Go 使用特定的参考时间进行格式化:2006-01-02 15:04:05
  • time.Now() 返回的是本地时间
  • 如果需要 UTC 时间,使用 time.Now().UTC()
  • 时间戳都是从 Unix 纪元(1970-01-01 UTC)开始计算的秒数/毫秒数等
    he