Go time.Parse()和ParseInLocation()的用法(附带实例)
在 Go 语言程序中,time 库中的 Parse() 函数可以解析格式化的时间字符串,并返回这个字符串代表的时间。
Parse() 函数的语法格式如下:
time 库还有一个与 Parse() 函数类似的 ParseInLocation() 函数。ParseInLocation() 函数的语法格式如下:
但是,Parse() 函数和 ParseInLocation() 函数也有不同之处,即:
在 Go 语言的 time 库中,有如下两个时区变量:
下面通过实例演示 Parse() 和 ParseInLocation() 函数的使用方法。代码如下:
Parse() 函数的语法格式如下:
func Parse(layout, value string) (Time, error)
time 库还有一个与 Parse() 函数类似的 ParseInLocation() 函数。ParseInLocation() 函数的语法格式如下:
func ParseInLocation(layout, value string, loc *Location) (Time, error)
但是,Parse() 函数和 ParseInLocation() 函数也有不同之处,即:
- 当缺少时区信息时,Parse() 函数将时间解释为 UTC 时间,而 ParseInLocation() 函数将时间解释为本地时间;
- 当时间字符串提供时区偏移量信息时,Parse() 函数尝试匹配 UTC 时间的时区,而 ParseInLocation() 则匹配本地时间的时区。
在 Go 语言的 time 库中,有如下两个时区变量:
- time.UTC:UTC时间;
- time.Local:本地时间。
下面通过实例演示 Parse() 和 ParseInLocation() 函数的使用方法。代码如下:
package main import ( "fmt" "time" ) func main() { var layout string = "2006-01-02 15:04:05" var timeStr string = "2023-09-29 17:37:58" // 使用 Parse 解析时间字符串(返回 UTC 时间) timeObj1, _ := time.Parse(layout, timeStr) fmt.Println(timeObj1) // 使用 ParseInLocation 解析时间字符串(返回本地时间) timeObj2, _ := time.ParseInLocation(layout, timeStr, time.Local) fmt.Println(timeObj2) }运行结果如下:
2023-09-29 17:37:58 +0000 UTC
2023-09-29 17:37:58 +0800 CST