2016-11-07 89 views
0

我一直在開發一個在golang中與mysql進行交互的微服務,我喜歡這個有才華的語言。無論如何有一個問題,不知道問題在哪裏,在我的代碼中,在MySQL驅動程序其他在MySQL中。所以,我的機器時區UTC + 3,我分享一些結果可能有助於Go MySql驅動程序沒有正確設置時間

//created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
mysql> select now(); 
"2016-11-07 22:43:02", //that is correct. 

中去

fmt.PrintLn(time.Now().Local()) 
"2016-11-07 22:51:02" //that is correct too 

但是,當我加入了實體到數據庫,MySQL工作臺顯示我錯了日期時間。

"2016-11-07 19:51:02" // 

Go代碼:

func (this *AppLogHandler) addLog(_log *AppLog) (int64, error){ 
    fmt.Println("addLog") 
    db:= this.Context.DB 
    stmt, err := db.Prepare("INSERT tbl_logs SET user_id=?,ip_proxy=?, ip_original=?, end_point=?, http_method=?, message=?, status=?, created_date=?") 
    if(err != nil){ 
     log.Println(err) 
     return -1, err 
    } 
    defer stmt.Close() 
    res, err := stmt.Exec(&_log.UserID, &_log.IPProxy, &_log.IPOriginal, &_log.Endpoint, &_log.HttpMethod, &_log.Message, &_log.Status, &_log.CreatedDate) 
    if(err != nil){ 
     log.Println(err) 
     return -1, err 
    } 
    return res.LastInsertId() 
} 

/// some code here 
    app_log := AppLog{} 
    app_log.IPProxy = r.RemoteAddr 
    app_log.IPOriginal = r.Header.Get("X-Forwarded-For") 
    app_log.CreatedDate = time.Now().Local() 
    app_log.UserID = user_id 
    app_log.Endpoint = r.URL.Path 
    app_log.HttpMethod = r.Method 
    fmt.Println(app_log.CreatedDate) 
    return this.addLog(&app_log) 

所以,球員,我需要你的幫助。幾個小時我無法解決問題。

mysql=> Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper 
go => 1.7 
mysql driver => 1.2, https://github.com/go-sql-driver/mysql/ 
+0

你是在同一臺機器上運行的嗎?如果在不同時區的計算機上運行,​​或者與其NTP服務器不同步,則可能會得到不同的結果。 –

+0

是的,在同一臺機器 – RockOnGom

+0

驅動程序可能會將它作爲字符串傳入,然後將其解析爲time.Time構造函數,將其轉換爲UTC。儘管time.Time#Local()返回一個time.Time。嗯 –

回答

1

MySQL驅動程序有一個configuration parameter for the default time zone,您可以設置爲time.Local(默認爲time.UTC)。當您保存該值時,它首先converts the time stamp to the UTC time zone,然後將其發送到數據庫。

正如評論中已經指出的那樣,一種更加可靠的方法是接受默認的Loc,並在數據庫中標準化UTC。這極大地簡化了與日期數學有關的任何事情,並且如果您只是在顯示該值時將其從UTC轉換爲本地,則不會對查看數據的人員的時區做出假設。

相關問題