Go語言程式獲取當前日期時間的各個組成部分
在本文中,我們將學習如何在 Go 語言中使用各種內部時間函式來獲取當前日期時間的各個組成部分。現在,我們將使用 time 包中的函式獲取當前日期時間,並使用各個組成部分作為方法來計算日期時間的各個組成部分。
語法
func Now() Time
Now() 函式定義在 time 包中。此函式生成當前本地時間。要使用此函式,我們必須首先在程式中匯入 time 包。
time.Month()
此方法屬於 time 包。它用於獲取當前月份作為 time.Month 值。
time.Day()
此方法是 time 包的一部分。它用於獲取當前日期作為 time.Day 值。
time.Hour()
此方法是 time 包的一部分。它用於獲取當前小時作為 time.Hour 值。
time.Minute()
此方法是 time 包的一部分。它用於獲取當前分鐘作為 time.Minute 值。
time.Second()
此方法是 time 包的一部分。它用於獲取當前秒作為 time.Second 值。
使用各個組成部分
在本例中,我們將編寫一個 Go 語言程式來使用各個組成部分獲取當前時間。這些組成部分將與儲存在變數中的當前時間一起使用。
演算法
步驟 1 - 在程式中匯入所需的包
步驟 2 - 建立一個主函式
步驟 3 - 在主函式中,使用內建函式獲取當前時間
步驟 4 - 從當前時間中使用內部函式檢索各個組成部分
步驟 5 - 使用 fmt 包中的 Printf 函式列印這些組成部分
示例
在下面的 Go 語言程式中,我們將瞭解如何使用各個組成部分獲取當前日期時間的各個組成部分
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
year := currentTime.Year()
month := currentTime.Month()
day := currentTime.Day()
hour := currentTime.Hour()
minute := currentTime.Minute()
second := currentTime.Second()
fmt.Println("The individual components can be represented as:")
fmt.Printf("Year: %d\n", year)
fmt.Printf("Month: %d\n", month)
fmt.Printf("Day: %d\n", day)
fmt.Printf("Hour: %d\n", hour)
fmt.Printf("Minute: %d\n", minute)
fmt.Printf("Second: %d\n", second)
}
輸出
The individual components can be represented as: Year: 2023 Month: 4 Day: 3 Hour: 4 Minute: 31 Second: 59
在當前時間上使用 Date 和 Clock 方法
在這種方法中,我們將編寫一個 Go 語言程式,使用 Date 和 Clock 方法在使用 Now 方法計算的當前時間上獲取當前日期時間的各個組成部分。
演算法
步驟 1 - 此程式在程式中匯入 fmt 和 time 包,其中 fmt 幫助格式化輸入和輸出,time 幫助獲取時間
步驟 2 - 建立一個主函式,在其中使用 time 包中的 Now 函式計算 current_time
步驟 3 - 獲取當前時間上的 Date、Clock 和 Zone 方法的各個組成部分
步驟 4 - 使用 fmt 包中的 Println 函式在控制檯上列印年份、月份、日期、小時、分鐘、秒和時區。
步驟 5 - 使用 %d 格式說明符在控制檯上列印數字。
示例
下面的 Go 語言程式說明了如何使用 Date 和 Clock 方法在當前時間上獲取當前日期時間的各個組成部分
package main
import (
"fmt"
"time"
)
func main() {
current_time := time.Now()
year, month, day := current_time.Date()
hour, minute, second := current_time.Clock()
zone, _ := current_time.Zone()
fmt.Printf("Year: %d\n", year)
fmt.Printf("Month: %d\n", month)
fmt.Printf("Day: %d\n", day)
fmt.Printf("Hour: %d\n", hour)
fmt.Printf("Minute: %d\n", minute)
fmt.Printf("Second: %d\n", second)
fmt.Printf("Timezone: %s\n", zone)
}
輸出
Year: 2023 Month: 4 Day: 3 Hour: 4 Minute: 33 Second: 6 Timezone: UTC
結論
我們編譯並執行了使用兩個示例獲取當前日期時間的各個組成部分的程式。在本例中,我們使用了與計算出的當前時間一起使用的內建元件,在第二個示例中,我們使用了 Date 和 Clock 方法來獲取日期和時間的各個組成部分。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP