使用Golang打印特定的日期时间的操作

Hana ·
更新时间:2024-05-15
· 278 次阅读

目录

基本时间操作

特定日期时间格式

自定义日期时间格式

解析不同格式的日期时间字符串

获取指定日期时间

基本时间操作

首先,我们来看一些基本的时间操作。

获取当前时间可以使用time.Now()函数,它会返回当前的时间对象,类型为time.Time。以下是一个示例:

package main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Current time is", currentTime) }

输出结果类似于:

Current time is 2022-05-24 11:07:36.710239 +0800 CST m=+0.000149139

这里的格式是默认的,如果我们想要按照特定的格式来输出时间,需要使用time.Format()函数

package main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Current time is", currentTime.Format("2006-01-02 15:04:05")) }

输出结果类似于:

Current time is 2022-05-24 11:08:11

这里使用了一个特殊的日期格式字符串"2006-01-02 15:04:05",它的含义是:

2006 表示年份

01 表示月份

02 表示日期

15 表示小时

04 表示分钟

05 表示秒钟

需要注意的是,格式字符串中的数字必须是这些特定的数字,否则会出现错误。

我们也可以使用time.Parse()函数将一个字符串转化为time.Time对象。

package main import ( "fmt" "time" ) func main() { timeStr := "2022-05-24 11:08:11" parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr) fmt.Println("Parsed time is", parsedTime) }

输出结果类似于:

Parsed time is 2023-05-24 11:08:11 +0000 UTC

特定日期时间格式

在上面的示例中,我们使用了一个特定的日期格式字符串。下面列举一些常用的特定日期时间格式:

2006-01-02:日期,如 2023-05-24

15:04:05:时间,如 11:08:11

2006-01-02 15:04:05:日期时间,如 2023-05-24 11:08:11

01/02/06 3:04 PM:美国日期时间格式,如 05/24/22 11:08 AM

02/01/2006 15:04:欧洲日期时间格式,如 24/05/2022 11:08

除了上面的格式外,Golang还提供了更丰富的特定日期时间格式,请参考官方文档了解更多信息。

自定义日期时间格式

如果上面提供的特定日期时间格式无法满足我们的需求,我们可以自定义日期时间格式。

package main import ( "fmt" "time" ) func main() { currentTime := time.Now() customFormat := "2006年01月02日 15点04分05秒" fmt.Println("Current time is", currentTime.Format(customFormat)) }

输出结果类似于

Current time is 2023年05月24日 11点14分53秒

解析不同格式的日期时间字符串

有时候我们会遇到各种各样的日期时间字符串格式,这时我们需要能够正确地解析它们

package main import ( "fmt" "time" ) func main() { timeStr := "2023-05-24 11:08:11" parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr) fmt.Println("Parsed time is", parsedTime) timeStr2 := "05/24/22 11:08 AM" parsedTime2, _ := time.Parse("01/02/06 3:04 PM", timeStr2) fmt.Println("Parsed time is", parsedTime2) timeStr3 := "2023年05月24日 11点14分53秒" parsedTime3, _ := time.Parse("2006年01月02日 15点04分05秒", timeStr3) fmt.Println("Parsed time is", parsedTime3) } 获取指定日期时间

有时候我们需要获取指定的日期时间,可以使用time.Date()函数。

package main import ( "fmt" "time" ) func main() { specTime := time.Date(2023, 5, 24, 12, 0, 0, 0, time.Local) fmt.Println("Specified time is", specTime.Format("2006-01-02 15:04:05")) }

输出结果类似于:

Specified time is 2022-05-24 12:00:00

到此这篇关于使用Golang打印特定的日期时间的操作的文章就介绍到这了,更多相关Golang打印特定的日期时间内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



日期时间 golang

需要 登录 后方可回复, 如果你还没有账号请 注册新账号