Golang时间函数

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

相关推荐
考虑考虑20 分钟前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
涡能增压发动积21 分钟前
一起来学 Langgraph [第三节]
后端
sky_ph34 分钟前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
开发者工具分享38 分钟前
如何应对敏捷转型中的团队阻力
开发语言
涡能增压发动积39 分钟前
一起来学 Langgraph [第二节]
后端
gregmankiw44 分钟前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
hello早上好1 小时前
Spring不同类型的ApplicationContext的创建方式
java·后端·架构
roman_日积跬步-终至千里1 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
秦少游在淮海1 小时前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5441 小时前
cpp自学 day2(—>运算符)
开发语言·c++