Go語言程式顯示當前日期和時間


在Go語言中,我們可以使用“now和format函式”、“now函式”和“strconv包”來顯示當前日期和時間。在本文中,我們將學習如何建立Go語言程式來使用各種示例顯示當前日期和時間。

語法

funcNow() Time

Now()函式在time包中定義。此函式生成當前本地時間。要使用此函式,我們必須首先在程式中匯入time包。

strconv.Quote()

此函式屬於strconv包。其目標是使用正確的轉義符和反斜槓返回帶引號的輸出。它以字串作為輸入。

time.Format()

此函式存在於time包中。它接受一個佈局輸入字串,該字串描述輸出字串的格式。

演算法

  • 步驟1 − 在程式中匯入所需的包

  • 步驟2 − 建立一個main函式

  • 步驟3 − 在main函式中使用內建函式獲取當前時間和日期

  • 步驟4 − 使用fmt包的Println函式列印當前時間和日期

示例1

在這個示例中,我們將使用time包中的Now函式來獲取當前時間和日期。我們將進一步對當前時間使用Format函式來獲取特定格式的日期和時間。

package main

import (
   "fmt"
   "time"
)

func main() {
   current_time := time.Now()
   fmt.Println("Current time along with the date is:", current_time.Format("2006-01-02 15:04:05"))
}

輸出

Current time along with the date is: 2009-11-10 23:00:00

示例2

在這個例子中,當前時間和日期是使用time包中的Now函式獲得的。此函式將返回time結構,該結構將確定當前日期和時間的格式。

package main

import (
   "fmt"
   "time"
)

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

輸出

Current Time and date is: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001

示例3

在這個特定的示例中,輸出將使用strconv包中的Quote函式用引號括起來,在此之前,當前時間將使用String函式轉換為字串。

package main

import (
   "fmt"
   "strconv"
   "time"
)

func main() {
   current_time := time.Now()
   fmt.Println("Current Time and date is:", strconv.Quote(current_time.String()))
}

輸出

Current Time and date is: "2009-11-10 23:00:00 +0000 UTC m=+0.000000001"

結論

我們執行了顯示當前日期和時間的程式。在第一個示例中,我們使用了time包中的Now函式以及日期格式化;在第二個示例中,我們只使用了Now函式;在第三個示例中,我們使用了Quote函式以及Now函式。

更新於:2023年5月3日

977 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告