如何在 Golang 中获取各种格式的当前日期和时间?


获取当前日期和时间是许多编程应用程序中的一项常见任务,从记录事件到计划任务。在本文中,我们将探讨如何在 Golang 中获取各种格式的当前日期和时间。

使用 Time 包

Golang 中的 time 包提供了一种简单的方法来处理日期和时间。我们可以使用 time.Now() 函数在本地时区获取当前日期和时间。

示例

以下是一个示例 -

package main

import (
   "fmt"
   "time"
)

func main() {
   now := time.Now()
   fmt.Println("Current date and time:", now)
}

在此代码中,我们使用 time.Now() 函数获取当前日期和时间,然后将其打印到控制台。

输出

Current date and time: 2023-05-04 16:59:03.598695926 +0000 UTC m=+0.000014238

格式化日期和时间

time 包还提供了一个 Format() 函数,允许我们以各种方式格式化日期和时间。我们可以使用布局字符串指定所需的格式。以下是一些常见的格式选项 -

  • 2023-04-14 - 年、月、日,格式为“YYYY-MM-DD”

  • 15:04:05 - 时、分、秒,格式为“HH:MM:SS”

  • Fri Apr 14 15:04:05 MST 2023 - 完整日期和时间,格式为“Fri Apr 14 15:04:05 MST 2023”

示例

以下是如何使用 Format() 函数格式化当前日期和时间的示例 -

package main

import (
   "fmt"
   "time"
)
func main() {
   now := time.Now()
   fmt.Println("Current date and time (RFC3339):", now.Format(time.RFC3339))
   fmt.Println("Current date (YYYY-MM-DD):", now.Format("2006-01-02"))
   fmt.Println("Current time (HH:MM:SS):", now.Format("15:04:05"))
   fmt.Println("Current date and time (Mon Jan 2 15:04:05 MST 2006):", now.Format("Mon Jan 2 15:04:05 MST 2006"))
}

在此代码中,我们使用 Format() 函数以各种方式格式化当前日期和时间。我们使用 time.RFC3339 常量以 RFC3339 格式格式化日期和时间。

输出

Current date and time (RFC3339): 2023-05-04T17:02:52Z
Current date (YYYY-MM-DD): 2023-05-04
Current time (HH:MM:SS): 17:02:52
Current date and time (Mon Jan 2 15:04:05 MST 2006): Thu May 4 17:02:52 UTC 2023

结论

使用 time 包,在 Golang 中获取各种格式的当前日期和时间非常简单直接。我们可以使用 time.Now() 函数在本地时区获取当前日期和时间,并使用 Format() 函数通过布局字符串以各种方式格式化日期和时间。

更新于: 2023-05-05

16K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.