将YYYYMMDD转换为Unix时间(Go语言)

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

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)

huangapple
  • 本文由 发表于 2017年4月20日 01:21:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/43502240.html
匿名

发表评论

匿名网友

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

确定