在 Go 中将时间转换为字符串
    
    
            Jay Singh
    2023年1月30日
    
    Go
    Go Time
    Go String
    Go Conversion
    
 
Datetime 是一种类型,表示某个时间点的日期和时间的属性。日期时间位于 Go 的 time 包中。
time 软件包包括你需要告诉、测量和显示时间的所有工具。time 包中还包含格式化、解析、显示和修改日期和时间的基本方法。
time.Time 是结构中将时间作为值保存的任何变量或字段的类型。时间是一种度量单位,表示时间的纳秒。
让我们看一下下面的一些例子。
在 Go 中使用 time.Now 显示当前时间
这个程序需要时间。使用 time 包中的新功能获取当前本地时间作为时间。
currentTime 变量用于存储时间值。fmt.Println 用于使用 currentTime.String() 输出作为字符串格式打印当前时间。
package main
import (
    "fmt"
    "time"
)
func main() {
    currentTime := time.Now()
    fmt.Println("The time is", currentTime.String())
}
输出:
The time is 2022-03-28 03:45:32 +0000 UTC m=+0.000000001
使用 Go 中的 time.Time.String() 函数将时间转换为字符串
在这种情况下,时间包提供计算和可视化时间的功能。Go 中的 time.String() 方法用于返回使用格式字符串准备的时间。
此外,此功能包含在 time 包中。
package main
import (
    "fmt"
    "time"
)
func main() {
    Time := time.Date(2022, 03, 28, 03, 50, 16, 0, time.UTC)
    t := Time.String()
    fmt.Printf("Time without nanoseconds is: %v\n", t)
}
输出:
Time without nanoseconds is: 2022-03-28 03:50:16 +0000 UTC
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe