Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go time.Parse() getting "month out of range" error

Tags:

time

go

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

like image 938
rafaelmorais Avatar asked Nov 04 '16 14:11

rafaelmorais


1 Answers

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

like image 89
nosequeldeebee Avatar answered Nov 12 '22 02:11

nosequeldeebee