Home >Backend Development >Golang >golang time.Parse error hour out of range same format

golang time.Parse error hour out of range same format

WBOY
WBOYforward
2024-02-06 09:20:071113browse

golang time.Parse错误小时超出范围相同格式

Question content

I have a time string in the following format: 31 July 2023 21:06:36. I want to free up time by using parsing. So I did this

    dateStr := "20 July 2023 21:06:36"
    formatLayout := "31 July 2023 21:06:36"
    parsedTime, err := time.Parse(formatLayout, dateStr)
    if err != nil {
        return detail, err
    }

But an error occurred parsing time "31 July 2023 21:06:36": hour out of range. Then I changed the format layout to 02 January 2006 15:04:05

    dateStr := "20 July 2023 21:06:36"
    formatLayout := "02 January 2006 15:04:05"
    parsedTime, err := time.Parse(formatLayout, dateStr)
    if err != nil {
        return detail, err
    }

It produces the correct time. My question is why if using the layout of 02 Jan 2006 15:04:05 it does not generate an error but 31 Jul 2023 21:06:36 does. They are in the same format, right?

Thank you


Correct answer


Mon Jan 2 15:04:05 MST 2006 (or 01/02 03: 04:05PM '06 -0700) is the time constant defined in the Layout package.

This is defined because each part of the time (day, month, year, hour, minute, second, time zone) is different, so it is convenient to use as a layout because it does not contain ambiguous fields. For example. The month is always 1, the day is always 2, and so on.

As you can see, this is the "special" time that the time package uses to perform parsing. Nothing more.

See also Origin of "Mon Jan 2 15:04:05 MST 2006", golang.

The above is the detailed content of golang time.Parse error hour out of range same format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete