19
votes

I'm new to Go and I was creating a little console script. You can check my code here:

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Calculate")
    fmt.Print("Hours and minutes: ")
    start, _, _ := reader.ReadLine()
    begin, err := time.Parse("2016-12-25 00:00:00", "2016-12-25 "+string(start)+":00")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(begin)
}

I've seen a related question but I couldn't understand why.

This is the error I'm getting after running my code:

parsing time "2016-12-25 22:40:00": month out of range
0001-01-01 00:00:00 +0000 UTC

Any ideas on what am I doing wrong?

Thanks

2
How about the latest version of this question from a day ago? stackoverflow.com/questions/40388246/… - JimB
So, it has to be that date specifically? :O - rafaelmorais
How else is the function supposed to know the difference in each field if there's no defined value? - JimB

2 Answers

28
votes

You're using the wrong reference time in the layout parameter of time.Parse which should be Jan 2, 2006 at 3:04pm (MST)

Change your begin line to the following and it will work:

begin, err := time.Parse("2006-01-02 15:04:05", "2016-12-25 "+string(start)+":00")

func Parse

0
votes

To avoid having to remember the special date, I usually wrap the logic in a function:

package main

import (
   "fmt"
   "time"
)

func parseDate(value string) (time.Time, error) {
   layout := time.RFC3339[:len(value)]
   return time.Parse(layout, value)
}

func main() {
   start := "15:04"
   d, e := parseDate("2016-12-25T" + start)
   if e != nil {
      panic(e)
   }
   fmt.Println(d)
}