解决XORM的时区问解决XORM的时区问题题vvvv

阿里云幸运券

如果你升级使用了较为新版xorm(如v0.6.3)和go-sql-driver(如v1.3)的go类库,那么你就可能会遇到时区问题。 如

time.Parse(“2006-01-02 15:04:05” ,“2018-01-15 12:11:12”) // 2018-01-15T12:11:12+00:00
写入是数据库时候就会被改变为2018-01-15T20:11:12+00:00。
上述的就是时区问题,因为我们使用的是东8时区,默认会被设置为0时区,解决方案很简单,只需要在main函数中或者main包中初始化时区:

time.LoadLocation(“Asia/Shanghai”)
数据库配置为

root:root@tcp(127.0.0.1:3306)/test?charset=utf8&interpolateParams=true
xorm的初始化修改为:

orm, err := initOrm(ds, maxIdleConn, maxOpenConn, debug)
if err != nil {
return nil, err
}
r.Value = orm
orm.DatabaseTZ = time.Local // 必须
orm.TZLocation = time.Local // 必须
orm.SetMaxIdleConns(maxIdleConn)
orm.SetMaxOpenConns(maxOpenConn)
字符串转换时间也需要改为

time.ParseInLocation(“2006-01-02 15:04:05” ,“2018-01-15 12:11:12”,time.Local)
此时写库时区问题就可以得到解决了,但是读库问题如下的的方式:

rss, err := this.Repo.Query(ctx, sqlStr, pos, now, os)
images := make([]*models.ImageConf, 0, len(rss))

for _, rs := range rss {
var tmpImage models.ImageConf
MapToStruct(rs, &tmpImage)
images = append(images, &tmpImage)
}

func MapToStruct(mapping map[string][]byte, j interface{}) {
elem := reflect.ValueOf(j).Elem()
for i := 0; i < elem.NumField(); i++ {
var key string
key = elem.Type().Field(i).Name
switch elem.Field(i).Interface().(type) {
case int, int8, int16, int32, int64:
x, _ := strconv.ParseInt(string(mapping[key]), 10, 64)
elem.Field(i).SetInt(x)
case string:
elem.Field(i).SetString(string(mapping[key]))
case float64:
x, _ := strconv.ParseFloat(string(mapping[key]), 64)
elem.Field(i).SetFloat(x)
case float32:
x, _ := strconv.ParseFloat(string(mapping[key]), 32)
elem.Field(i).SetFloat(x)
case time.Time:
timeStr := string(mapping[key])
timeDB, err := time.ParseInLocation(“2006-01-02 15:04:05”, timeStr, time.Local)
if err != nil {
timeDB, err = time.ParseInLocation(“2006-01-02”, timeStr, time.Local)
if err != nil {
timeDB, err = time.ParseInLocation(“15:04:05”, timeStr, time.Local)
} else {
timeDB = time.Date(0, 0, 0, 0, 0, 0, 1, time.Local)
}
}
elem.Field(i).Set(reflect.ValueOf(timeDB))
}
}
}
其中MapToStruct函数中的time.Time类型这儿有一个需要我们注意的,如果配置的数据库为

root:root@tcp(127.0.0.1:3306)/test?charset=utf8&interpolateParams=true&parseTime=true&loc=Local
多出了&parseTime=true&loc=Local此时timeStr := string(mapping[key])得到的将会是2006-01-02T15:04:05+08:00。
那么你的转换格式应该为2006-01-02T15:04:05+08:00。

总结一下:

在项目中时区一定要在项目初始化时候就已经设置好
字符串转换时间尽可能使用time.ParseInLocation
parseTime=true&loc=Local或者parseTime=true&loc=Asia%2FShanghai对xorm解析时间类型为map[string][]byte有着影响

腾讯云代金券

原文链接

https://blog.51cto.com/qiangmzsx/2061278

服务推荐

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值