wx

关注公众号

time


Golang 标准库 - time

time 包提供了测量和显示时间的功能。日历计算采用公历,即使历史日期也是如此。

主要功能说明:

  1. 获取时间

    • Now() 获取当前时间
    • Date() 创建指定时间
    • Unix() 从时间戳创建
  2. 时间格式化与解析

    • Format() 按指定格式输出
    • Parse() 解析时间字符串
    • 使用参考时间 “2006-01-02 15:04:05”
  3. 时间运算

    • Add() 增加时间
    • Sub() 计算时间差
    • AddDate() 增加年月日
  4. 定时器

    • Sleep() 睡眠
    • After() 延迟通道
    • Tick() 周期通道
    • NewTimer()/NewTicker() 定时器

func main() {
	// 1. 获取当前时间
	fmt.Println("=== 获取时间 ===")
	now := time.Now()
	fmt.Println("当前时间:", now)
	fmt.Println("年:", now.Year())
	fmt.Println("月:", now.Month())
	fmt.Println("日:", now.Day())
	fmt.Println("时:", now.Hour())
	fmt.Println("分:", now.Minute())
	fmt.Println("秒:", now.Second())

	// 2. 时间格式化
	fmt.Println("\n=== 时间格式化 ===")
	// 使用参考时间: Mon Jan 2 15:04:05 MST 2006
	fmt.Println(now.Format("2006-01-02 15:04:05"))
	fmt.Println(now.Format("2006/01/02"))
	fmt.Println(now.Format("15:04:05"))

	// 3. 时间解析
	fmt.Println("\n=== 时间解析 ===")
	t, err := time.Parse("2006-01-02", "2024-03-15")
	if err != nil {
		fmt.Println("解析错误:", err)
	} else {
		fmt.Println("解析结果:", t)
	}

	// 4. 时间运算
	fmt.Println("\n=== 时间运算 ===")
	future := now.Add(24 * time.Hour)
	fmt.Println("24小时后:", future)

	past := now.AddDate(0, -1, 0) // 减一个月
	fmt.Println("一个月前:", past)

	diff := future.Sub(now)
	fmt.Println("时间差:", diff)
	fmt.Println("小时数:", diff.Hours())

	// 5. 时间戳
	fmt.Println("\n=== 时间戳 ===")
	fmt.Println("Unix时间戳:", now.Unix())
	fmt.Println("Unix毫秒:", now.UnixMilli())
	fmt.Println("Unix微秒:", now.UnixMicro())

	// 从时间戳创建
	tFromUnix := time.Unix(1700000000, 0)
	fmt.Println("从时间戳创建:", tFromUnix)
}
如有疑问关注公众号给我留言
wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo