将Go的时间输出为RFC3339格式,类似于MySQL的格式。

huangapple go评论89阅读模式
英文:

Output Go time in RFC3339 like MySQL format

问题

在Go语言中,你可以使用time包来格式化日期和时间。根据你的代码,你可以使用以下方式来格式化日期和时间为"YYYY-MM-DD HH:MM:SS"的格式:

createdTime := time.Unix(0, p.Created)
formattedTime := createdTime.Format("2006-01-02 15:04:05")
fmt.Println(formattedTime)

这里的"2006-01-02 15:04:05"是Go语言中的日期和时间格式化模板,它是固定的。你只需要将这个模板传递给Format方法,然后将时间对象格式化为指定的格式即可。

希望对你有帮助!如果你还有其他问题,请随时提问。

英文:

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

得分: 16

上述代码中有两个错误。对于格式,你需要将特定日期/时间的输出格式化,而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))
英文:

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

答案2

得分: 0

使用当前时间非常简单

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

fmt.Println(timestamp)

英文:

Using the current time is just as easy

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

fmt.Println(timestamp)

huangapple
  • 本文由 发表于 2014年2月9日 00:50:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/21648842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定