如何在 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() 函式透過佈局字串以各種方式格式化日期和時間。
廣告