mysql - Go MySql 驱动程序没有正确设置时间

标签 mysql go

我一直在用golang开发一个与mysql交互的微服务有一段时间了,我喜欢这种有才华的语言。无论如何有问题,不知道问题出在哪里,在我的代码中,在 mysql 的 mysql 驱动程序中。所以我的机器时区 utc+3,我正在分享一些结果,可能会有帮助

//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 workbench 显示错误的日期时间。

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

去代码:

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 转换为本地时间,则不会对查看数据的人的时区做出假设。

关于mysql - Go MySql 驱动程序没有正确设置时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473565/

相关文章:

php - Mysql查询匹配多个可能的字符

php - 在 codeigniter 中按限制排序

php - MySQL php INSERT INTO 需要很长时间

pointers - Golang、指针、函数

golang Unmarshal Struct In Function 不知道类型和依赖接口(interface)

go - 字符串和整数连接问题golang

php - 上传过程不在数据库中保存正确的名称

javascript - 将对象拆分成更小的部分

go - else 之前意外的分号或换行符,即使 else 之前都没有 if

http - 使用 Golang Gorilla 包设置回调