英文:
Convert YYYYMMDD to Unix time in Go
问题
我有一个表单输入,我觉得对用户来说,最简单的方式就是直接插入日期,格式为YYYYMMDD,所以我想知道如何将用户输入转换为Unix时间?
import "time"
func SomeFormPOST(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
// 错误处理
date := r.FormValue("date")
unixDate := date.DOWHAT.Unix()
}
我认为可能需要使用 t, _ = time.Parse(...)
,但是我还没有弄清楚如何做到这一点。
英文:
I have a form input where I figure it would be easiest for the user to simply insert date as YYYYMMDD, so I was wondering how I should go about converting that user input to Unix time?
import "time"
func SomeFormPOST(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
// err handling
date := r.FormValue("date")
unixDate := date.DOWHAT.Unix()
}
I think maybe I need to use t, _ = time.Parse(...)
but not haven't been able to figure it out..
答案1
得分: 1
你是正确的,你可以使用 time.Parse 函数,其中第一个参数是第二个参数的布局,第二个参数是你想要解析的值。
这意味着,如果你知道要解析的值具有 YYYYMMDD
格式,你可以使用参考时间来构建布局参数。由于参考时间在文档中指定为 Mon Jan 2 15:04:05 -0700 MST 2006
,所以你的布局应该是 20060102
。
layout := "20060102"
t, err := time.Parse(layout, date)
if err != nil {
panic(err)
}
fmt.Println(t)
英文:
You are correct, you can use time.Parse, where the first argument is the layout of the second, the second being the value you want to parse.
That means that if you know that the value you want to parse has this YYYYMMDD
format you can use the reference time to construct the layout argument. And since the reference time is specified in the docs as Mon Jan 2 15:04:05 -0700 MST 2006
your layout should look like this: 20060102
.
layout := "20060102"
t, err := time.Parse(layout, date)
if err != nil {
panic(err)
}
fmt.Println(t)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论