Golang常用的时间函数
            
            
              Go
              
              
            
          
          package main
import (
	"fmt"
	"time"
)
func main() {
	// 获取当前时间
	now := time.Now()
	// 当前时间的不同格式
	fmt.Println("现在的时间是:", now.Format("2006-01-02 15:04:05"))
	fmt.Println("今天的日期是:", now.Format("2006-01-02"))
	fmt.Println("现在的时间戳是:", now.Unix())
	// 时间加减法
	fmt.Println("昨天是:", now.AddDate(0, 0, -1).Format("2006-01-02 15:04:05"))
	fmt.Println("明天是:", now.AddDate(0, 0, 1).Format("2006-01-02 15:04:05"))
	fmt.Println("上个月是:", now.AddDate(0, -1, 0).Format("2006-01-02 15:04:05"))
	fmt.Println("下个月是:", now.AddDate(0, 1, 0).Format("2006-01-02 15:04:05"))
	fmt.Println("去年是:", now.AddDate(-1, 0, 0).Format("2006-01-02 15:04:05"))
	fmt.Println("明年是:", now.AddDate(1, 0, 0).Format("2006-01-02 15:04:05"))
	// 时间解析,注意的是解析出来是utc时间,也可以指定当前时区进行解析
	timeStr := "2024-12-11 11:40:14"
	parseTime, _ := time.Parse("2006-01-02 15:04:05", timeStr)
	fmt.Printf("%v 时间解析成功:%v\n", timeStr, parseTime.String())
	parseLocalTime, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	fmt.Printf("%v 时间解析为当地时间成功:%v\n", timeStr, parseLocalTime.String())
	// 时间戳解析
	timestamp := 1731296414
	unixTime := time.Unix(int64(timestamp), 0)
	fmt.Printf("%v 时间戳解析成功:%v\n", timestamp, unixTime.String())
	// 指定时区转换
	// 加载时区 北京时间
	bjloc, _ := time.LoadLocation("Asia/Shanghai")
	fmt.Println("现在的北京时间是:", now.In(bjloc).Format("2006-01-02 15:04:05"))
	// 加载时区 韩国时间
	hgloc, _ := time.LoadLocation("Asia/Seoul")
	fmt.Println("现在的韩国时间是:", now.In(hgloc).Format("2006-01-02 15:04:05"))
}
        输出结果:
现在的时间是: 2024-11-11 13:32:26
今天的日期是: 2024-11-11
现在的时间戳是: 1731303146
昨天是: 2024-11-10 13:32:26
明天是: 2024-11-12 13:32:26
上个月是: 2024-10-11 13:32:26
下个月是: 2024-12-11 13:32:26
去年是: 2023-11-11 13:32:26
明年是: 2025-11-11 13:32:26
2024-12-11 11:40:14 时间解析成功:2024-12-11 11:40:14 +0000 UTC
2024-12-11 11:40:14 时间解析为当地时间成功:2024-12-11 11:40:14 +0800 CST
1731296414 时间戳解析成功:2024-11-11 11:40:14 +0800 CST
现在的北京时间是: 2024-11-11 13:32:26
现在的韩国时间是: 2024-11-11 14:32:26