解决XORM的时区问题
发布时间:2020-12-16 09:39:40 所属栏目:大数据 来源:网络整理
导读:如果你升级使用了较为新版 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
如果你升级使用了较为新版 time.Parse("2006-01-02 15:04:05","2018-01-15 12:11:12") // 2018-01-15T12:11:12+00:00 写入是数据库时候就会被改变为 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,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,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",time.Local) if err != nil { timeDB,err = time.ParseInLocation("15:04:05",time.Local) } else { timeDB = time.Date(0,1,time.Local) } } elem.Field(i).Set(reflect.ValueOf(timeDB)) } } } 其中 root:root@tcp(127.0.0.1:3306)/test?charset=utf8&interpolateParams=true&parseTime=true&loc=Local 多出了 总结一下:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |