5

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.

2 Answers2

16

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))
Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
  • That worked, thanks. Weird that the docs state `func Unix(sec int64, nsec int64) Time` tho. Probably understand it wrong –  Feb 08 '14 at 17:07
  • `sec` is the number of seconds since the epoch; `nsec` is the number of nano-seconds after `sec`. – publysher Feb 09 '14 at 09:51
  • re the comment - I'm not sure that Mountain Standard Time is useful in Holland ;-P – Rick-777 Feb 10 '14 at 22:47
  • 1
    @Rick-777 see the [documention](http://golang.org/pkg/time/#pkg-constants), the comment is the reference time used in format strings, it is defined as -0700 == MST and has nothing whatsoever to do with current timezone. – Dave C Feb 10 '14 at 23:52
0

Using the current time is just as easy

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

fmt.Println(timestamp)

Nixon Kosgei
  • 788
  • 8
  • 13