简体   繁体   中英

Getting “hour out of range” on time.Parse(layout, value) in Go

I am getting the error hour out of range while trying to parse a timestamp string with the following code:

package main

import (
    "log"
    "time"
)

func main() {
    layout := "2006-01-02 15:04:05 +0530"
    timeStr := "2020-05-23 22:55:51 +0530"
    t, tErr := time.Parse(layout, timeStr)
    log.Printf("Layout: %s", layout)
    log.Printf("Time (string): %s", timeStr)
    log.Printf("Time (time.Time): %s", t.String())
    if tErr != nil {
        log.Printf("Error: %s", tErr.Error())
    }
}

Playground: https://goplay.space/#SIWJWKduPQg

Repeat of / Similar to: Hour out of range on time.parse in golang

You should use the proper format constant for parsing.

For Numeric time zone offsets in https://golang.org/src/time/format.go

Numeric time zone offsets format as follows:
    -0700  ±hhmm
    -07:00 ±hh:m
    -07    ±hh

Here for parsing ±hhmm you should use exact format -0700 . So use -0700 instead of +0530 in parsing format

layout := "2006-01-02 15:04:05 -0700"

The timezone offset in the layout should be -0700 not +0530

layout := "2006-01-02 15:04:05 -0700"

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