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.

有帮助吗?

解决方案

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

其他提示

Using the current time is just as easy

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

fmt.Println(timestamp)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top