简体   繁体   English

按时获取“小时超出范围”。Go 中的解析(布局,值)

[英]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:尝试使用以下代码解析时间戳字符串时,错误hour out of range

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游乐场: https://goplay.space/#SIWJWKduPQg

Repeat of / Similar to: Hour out of range on time.parse in golang重复/类似于: 时间超出范围的时间。在 golang 中解析

You should use the proper format constant for parsing.您应该使用正确的格式常量进行解析。

For Numeric time zone offsets in https://golang.org/src/time/format.go对于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 .在这里解析±hhmm你应该使用精确的格式-0700 So use -0700 instead of +0530 in parsing format所以在解析格式中使用-0700而不是+0530

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

The timezone offset in the layout should be -0700 not +0530布局中的时区偏移量应为-0700而不是+0530

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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