time Parse 默认解析字符串的时区为UTC,如何转换为本地时间?

根据time package

time package 中关于Parse Function的说明如下:

In the absence of a time zone indicator, Parse returns a time in UTC.

也就是说通过Parse解析时间字符串,自动采用UTC(协调世界时)

但UTC的时间不等于本地时间,怎么办?

使用time.Date函数 (func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time) 

代码如下:

t, err := time.Parse("2006-01-02T15:04", s)   

if err == nil {       

t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)       

return &t   

}


参考资料:

【1】time.Parse and Location [groups.google]

【2】time.go源码 -- 代码中有关于t.Local的说明

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容