dongtan8979 2014-02-08 16:50
浏览 181
已采纳

像MySQL格式一样以RFC3339输出输出时间

In Holland we mostly use YYYY-MM-DD HH:MM:SS. How can I format that in Go? Everything I insert (even according the standard) gives weird numbers.

This is my code (p.Created is a NanoSeconds int64 object):

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))
}

I could just concat time.Unix(0, p.Created).Year() etc., but that's not very clean and is an annoyance for consistency.

  • 写回答

1条回答 默认 最新

  • dongzhou4727 2014-02-08 17:01
    关注

    There were two mistakes in the above. For the format you need to make the output of that special date/time, and the parameters to time.Unix are the other way round (playground)

    const createdFormat = "2006-01-02 15:04:05" //"Jan 2, 2006 at 3:04pm (MST)"
    
    fmt.Println(time.Unix(1391878657, 0).Format(createdFormat))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器