Go时间格式化,Go 字符串转时间格式相互转换

更新于 2022-08-13 17:21 180
专栏: Golang 标签: Go

字符串转时间格式

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)

结果:


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, // 错误示例
 


时间格式转字符串