超出时间的小时数.在golang中解析 [英] Hour out of range on time.parse in golang

查看:85
本文介绍了超出时间的小时数.在golang中解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析日期时间字符串.我将确切的字符串作为格式传递,并且获取和错误解析时间为"01/31/2000 12:59 AM":超出范围的小时.我正在从输入中获取该字符串.我该如何进行这项工作?

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?

这里是代码( 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)
    }
}

推荐答案

基于共享代码,应将布局更改为 2006年1月2日上午03:04 进行修复:

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

注意:如果您使用的是24小时制,则应将布局中的小时部分更改为 15而不是03 ,并摆脱 AM 部分,例如 01/02/2006 15:04

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 e.g. 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.

这篇关于超出时间的小时数.在golang中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆