-5

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

fisker
  • 979
  • 4
  • 18
  • 28
  • Did you try reading the manual? – Jonathan Hall Apr 19 '17 at 17:34
  • 2
    This has so many duplicates that it's just ridiculous. Google exists for a reason people. – RayfenWindspear Apr 19 '17 at 17:41
  • 1
    I don't see how the question marked as answered is the same, and I did Google for it beforehand, as well as check the time docs.. there will probably be over a thousand people who want to do exactly what I asked so why are you so negative about me wanting to get more questions/answers related to Go which will help increase its popularity.. – fisker Apr 19 '17 at 18:12
  • @fisker: Yes, there are a thousand people who want t odo exactly the same as you. Which is why it's so incredible that you didn't find an answer. But fear not: We've now provided you a link to one of the exact duplicates. – Jonathan Hall Apr 19 '17 at 18:16
  • Except it's not a duplicate, his input string is completely different, and it has nothing to do with obtaining the value as Unix timestamp – fisker Apr 19 '17 at 18:18

1 Answers1

1

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)
mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • Thanks a lot, I remember trying something similar, but after converting it back and fourth between Unix timestamp then it appeared to give different results.. not sure if it was because I wrote the layout string differently (e.g. 20160319) but it seems to work now :) – fisker Apr 19 '17 at 18:24
  • No problem, the reference timestamp is important for the layout, you have to use `01` as the month, `02` as the day, `2006` as the year, and so forth... If you used `03` as month, it's just not gonna work. – mkopriva Apr 19 '17 at 18:28
  • Ahh, that explains it :).. I figured it was best if I used something between 13-31 as day so that it couldn't be confused as the month.. – fisker Apr 19 '17 at 18:30