duan1226 2015-08-15 04:02 采纳率: 100%
浏览 64
已采纳

我怎么不能将已经存在的RFC3339字符串解析回RFC3339字符串?

I'm storing a variable into a MySQL database with the field type of VARCHAR(255) like this:

ts, err := time.Parse(time.RFC3339, nonce[0:20])

which works great and shows up like this:

pic1

Then when I need to get it from the database I do this:

rows, err := db.Query("SELECT nonce, time FROM noncestore WHERE endpoint=?", endpoint)

        var sTimeStamp, nonceHolder string
        for rows.Next() {
                err = rows.Scan(&nonceHolder, &sTimeStamp)
                errCheck(err)

Gives error//>> timeStamp, err := time.Parse(time.RFC3339, sTimeStamp)
                errCheck(err)

                if timeStamp == ts && nonceHolder == s {
                        return errors.New("Nonce already used")
                }

                if now.Sub(timeStamp) < *maxNonceAge {
                        _, err := db.Query("INSERT INTO noncestore SET nonce=?, time=?, endpoint=?", nonceHolder, sTimeStamp, endpoint)
                        errCheck(err)
                }
        }

The line noted above gives me this error:

2015/08/14 21:56:18 http: panic serving [::1]:49663: Failed: parsing time "2015-08-15 03:56:00" as "2006-01-02T15:04:05Z07:00": cannot parse " 03:56:00" as "T"

How come it is able to convert it to RFC3339 and store it in the database, but when it comes time to get it and format it back to RFC3339 so that I can use in my if statement I get an error?

  • 写回答

1条回答 默认 最新

  • duankang5285 2015-08-15 05:37
    关注

    It looks like your database driver returns times in a format that's not in RFC3339. Instead of using

    timeStamp, err := time.Parse(time.RFC3339, sTimeStamp)
    

    try using

    timeStamp, err := time.Parse("2006-01-02 15:04:05", sTimeStamp)
    

    An important thing to remember is that the database itself is not going to store raw strings at all, RFC3339 or otherwise. It has its own internal representation of time, and when you query for it, the value you get depends on how that db wishes to reperesent it to you. In this case, it's chosen a somewhat different format, which the format string I've pasted above (the one that starts with "2006-01-02...") should fix. And yes, in Go, date format strings look like dates themselves.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?