Go MySql驱动程序没有正确设置时间
问题描述:
我一直在开发一个在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/
答
MySQL驱动程序有一个configuration parameter for the default time zone,您可以设置为time.Local
(默认为time.UTC
)。当您保存该值时,它首先converts the time stamp to the UTC time zone,然后将其发送到数据库。
正如评论中已经指出的那样,一种更加可靠的方法是接受默认的Loc
,并在数据库中标准化UTC。这极大地简化了与日期数学有关的任何事情,并且如果您只是在显示该值时将其从UTC转换为本地,则不会对查看数据的人员的时区做出假设。
你是在同一台机器上运行的吗?如果在不同时区的计算机上运行,或者与其NTP服务器不同步,则可能会得到不同的结果。 –
是的,在同一台机器 – RockOnGom
驱动程序可能会将它作为字符串传入,然后将其解析为time.Time构造函数,将其转换为UTC。尽管time.Time#Local()返回一个time.Time。嗯 –