如果你升級使用了較為新版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
有著影響另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
分享標題:解決XORM的時區問題-創新互聯
文章來源:http://m.kartarina.com/article4/ccghie.html
成都網站建設公司_創新互聯,為您提供小程序開發、定制網站、虛擬主機、靜態網站、動態網站、網站改版
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯