分享
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
## 日期解析
## 背景
当有一个日期字符串(2014年11月12日 11:45:26)需要转化为Go的time类型,我们第一时间肯定会想到time包的Parse方法,指定字符串的格式layout:
```go
layout := "2006年01月02日 15:04:05"
str := "2014年11月12日 11:45:26"
t, err := time.Parse(layout, str)
```
但是,有个容易忽略的问题,go语言默认的时区用的是**UTC**,而我们一般要的是**本地时区**,可以看一下源码:
```go
package time
func Parse(layout, value string) (Time, error) {
return parse(layout, value, UTC, Local)
}
```
这个又和获取当前时间(time.Now)不同,time.Now用的又是本地时区:
```go
var Local *Location = &localLoc
func Now() Time {
sec, nsec, mono := now()
mono -= startNano
sec += unixToInternal - minWall
if uint64(sec)>>33 != 0 {
return Time{uint64(nsec), sec + minWall, Local}
}
return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local}
}
```
## 解决方案
这时需要用ParseInLocation方法,指定时区为time.Local
```go
layout := "2006年01月02日 15:04:05"
str := "2014年11月12日 11:45:26"
t, err := time.ParseInLocation(layout, str, time.Local)
```
另外有更好的方式,日期格式化的时候也加上时区例如:2006年01月02日T15:04:05-0700,这样time.Parse 就能正确转化为指定时区:
```go
format:="2006年01月02日T15:04:05-0700" // 0700 表示时区
str := time.Now().Format(format)
fmt.Println(str) // 输出:2021年05月08日T15:53:33+0800
t, _ := time.Parse(format, str)
fmt.Println(t) // 输出:2021年05月08日 15:53:33 +0800 CST
```
## 总结
如果系统要支持国外和国内用户,建议是格式化采用:2006年01月02日T15:04:05-0700,带时区的格式化,这样就能避免时区的解析错误问题
**我的博客:** [Go时区Parse的坑 | 艺术码农的小栈](https://itart.cn/blogs/2021/practice/go-zone-parse-error.html)
有疑问加站长微信联系(非本文作者))
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1444 次点击 ∙ 1 赞
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传