英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论