Golang解決XORM的時區問題

qiangmzsx發表於2018-01-16

如果你升級使用了較為新版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%2FShanghaixorm解析時間型別為map[string][]byte有著影響
更多原創文章乾貨分享,請關注公眾號
  • Golang解決XORM的時區問題
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章