简体   繁体   中英

Hour out of range on time.parse in golang

I am trying to parse a date time string in go. I pass the exact string as the format and get and error parsing time "01/31/2000 12:59 AM": hour out of range. I am getting that string from an input. How can I make this work?

Here is the code ( https://play.golang.org/p/Kg9KfFpU2z )

func main() {
    layout := "01/31/2000 12:59 AM"
    if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
        fmt.Println("Time decoded:", t)
    } else {
        fmt.Println("Failed to decode time:", err)
    }
}

Based on your shared code, you should change the layout to 01/02/2006 03:04 AM to fix it:

Note: If you have 24 hours format, you should change the hour part in layout to 15 instead of 03 and also to get rid of AM part eg 01/02/2006 15:04

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "01/02/2006 03:04 AM"
    if t, err := time.Parse(layout, "01/31/2000 12:59 AM"); err == nil {
        fmt.Println("Time decoded:", t)
    } else {
        fmt.Println("Failed to decode time:", err)
    }
}

Here is a good article that would help you to understand different layouts.

Your format needs to use a very specific date and time, see the docs:

https://golang.org/pkg/time/#example_Parse

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

So you need https://play.golang.org/p/c_Xc_R2OHb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM