在荷兰,我们大多使用YYYY-MM-DD HH:MM:SS。如何在Go中格式化?我插入的所有内容(即使按照标准)都会给出奇怪的数字。
这是我的代码(p.Created
是NanoSeconds 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()
等,但这不是很干净,并且是一致的烦恼。
答案 0 :(得分:14)
上面有两个错误。对于您需要输出特殊日期/时间的格式,以及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))