实例如下:
local, _ := time.LoadLocation("Asia/Shanghai")
showTime, _ := time.ParseInLocation("2006-01-02 15:04:05", "2021-11-07 11:34:00", local)
fmt.Printf("showTime=%v, type=%T,\n", showTime, showTime)
showTime, _ = time.ParseInLocation("2006-01-02", "2021-11-07", local)
fmt.Printf("showTime=%v, type=%T,\n", showTime, showTime)
showTime, _ = time.ParseInLocation("2006-01-02 15:04:05", "2021-11-07", local)
fmt.Printf("showTime=%v, type=%T,\n", showTime, showTime)
输出结果如下:
[root@localhost src]# ./test
showTime=2021-11-07 11:34:00 +0800 CST, type=time.Time,
showTime=2021-11-07 00:00:00 +0800 CST, type=time.Time,
showTime=0001-01-01 00:00:00 +0000 UTC, type=time.Time,
注意事项
需要转换的 字符串 必须和时间常量 格式一致
正确例子:
"2006-01-02 15:04:05", "2021-11-07 11:34:00"
"2006-01-02", "2021-11-07"
错误例子:
"2006-01-02 15:04:05", "2021-11-07"