【问题标题】:Output Go time in RFC3339 like MySQL format以 RFC3339 格式输出 Go 时间,如 MySQL 格式
【发布时间】:2014-02-08 16:50:47
【问题描述】:

在荷兰,我们主要使用 YYYY-MM-DD HH:MM:SS。如何在 Go 中格式化?我插入的所有内容(即使根据标准)都会给出奇怪的数字。

这是我的代码(p.CreatedNanoSeconds int64 对象):

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)

const createdFormat = "2010-01-01 20:01:00" //"Jan 2, 2006 at 3:04pm (MST)"

type Post struct {
    Id      int64
    Created int64
    Title   string
    Body    string
}

func main() {
    // Establish database connection
    dsn := "root@tcp(127.0.0.1:3306)/testdb"
    con, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Println("Couldn't connect to databse:", err)
    } else {
        log.Println("DB Connection established")
    }
    defer con.Close()

    // Try to get something
    row := con.QueryRow("SELECT * FROM posts LIMIT 1")
    p := new(Post)
    err = row.Scan(&p.Id, &p.Created, &p.Title, &p.Body)

    if err != nil {
        log.Println("Failed to fetch Post")
    }
    fmt.Println(p)
    fmt.Println(time.Unix(0, p.Created).Format(createdFormat))
}

我可以只连接 time.Unix(0, p.Created).Year() 等,但这不是很干净,而且不利于一致性。

【问题讨论】:

    标签: go rfc3339


    【解决方案1】:

    上面有两个错误。对于您需要输出该特殊日期/时间的格式,time.Unix 的参数是相反的 (playground)

    const createdFormat = "2006-01-02 15:04:05" //"Jan 2, 2006 at 3:04pm (MST)"
    
    fmt.Println(time.Unix(1391878657, 0).Format(createdFormat))
    

    【讨论】:

    • 成功了,谢谢。奇怪的是文档状态func Unix(sec int64, nsec int64) Time tho。大概理解错了
    • sec 是自纪元以来的秒数; nsecsec 之后的纳秒数。
    • 重新评论 - 我不确定山地标准时间在荷兰是否有用;-P
    • @Rick-777 见documention,注释是格式字符串中使用的参考时间,定义为-0700 == MST,与当前时区无关。跨度>
    【解决方案2】:

    使用当前时间同样简单

    timestamp := time.Now().Format("2006-01-02 15:04:05")
    
    fmt.Println(timestamp)
    
    

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 2016-09-03
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2020-10-27
      相关资源
      最近更新 更多