3
votes

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

2

2 Answers

2
votes

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"
1
votes

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

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