Golang无法解析时间。

huangapple go评论72阅读模式
英文:

Golang unable to parse time

问题

我正在创建一个Go脚本,试图解析日期时间字符串。

我的日期时间从客户端传入,格式如下:

2023-01-31T10:44:59.800

我创建了一个基本的布局,并尝试使用time.Parse进行解析:

t, err := time.Parse("2006-01-02 15:04:05 pm", s)
if err != nil {
    return time.Time{}, fmt.Errorf("无法解析时间 %q", s)
}

从中,我收到一个无法解析时间的错误。

我尝试删除日期时间字符串中的 T,但得到相同的输出。

我的布局是否需要做出一些不同的调整?或许 pm 是无效的?

由于错误信息相当模糊,我很难确定实际的问题所在。

英文:

I am creating a Go script that attempts to parse date time strings.

My date time comes in from my client like

2023-01-31T10:44:59.800

I create a basic layout and attempt to parse with time.Parse

	t, err := time.Parse("2006-01-02 15:04:05 pm", s)
	if err != nil {
		return time.Time{}, fmt.Errorf("could not parse time %q", s)
	}

From this, I receive an error that the time cannot be parsed.

I have tried removing the T from my date time string but get the same output.

Is there something different I need for my layout? Potentially the pm is invalid?

I am struggling to work out the actual issue as the error is quite vague

答案1

得分: 5

你的解析字符串需要与时间的格式匹配。

字符串"2006-01-02T15:04:05.000"包括T、毫秒,并省略了“pm”。然后,它将正确解析时间为2023-01-31 10:44:59.8 +0000 UTC

在playground上试一试

英文:

Your parse string needs to match the format of your time.

The string "2006-01-02T15:04:05.000" includes the T, the milliseconds, and omits the ' pm'. It will then parse the time properly as 2023-01-31 10:44:59.8 +0000 UTC

try it out on the playground

huangapple
  • 本文由 发表于 2023年3月22日 21:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75813237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定