将字符串解析为时间

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

Go parse string to time

问题

我有以下字符串:

Sun, 03 Jan 2016 10:00:07 CET

我想将其解析为时间,但似乎无法弄清楚如何编写格式。

这是我目前的代码:

layout := "Mon, 01 Jan 03:04:05"
t, _ := time.Parse(layout, "Sun, 03 Jan 2016 10:00:07 CET")
fmt.Println(t)

我得到的输出是:

0001-01-01 00:00:00 +0000 UTC
英文:

I've got the following string:

Sun, 03 Jan 2016 10:00:07 CET

Id like to parse it into time, but cannot seem to figure out how to write the format.

This is what I've got so far:

layout := "Mon, 01 Jan 03:04:05"
t, _ := time.Parse(layout, "Sun, 03 Jan 2016 10:00:07 CET")
fmt.Println(t)

Output I get is:

0001-01-01 00:00:00 +0000 UTC

答案1

得分: 3

首先:你正在默默地忽略time.Parse返回的错误作为第二个返回值。我建议适当地处理这个错误。

其次,让我们来看一下time.Parse的文档:

Parse函数解析一个格式化的字符串并返回它表示的时间值。布局定义了格式,通过展示如果Mon Jan 2 15:04:05 -0700 MST 2006是值的话,它将如何被解释;它作为输入格式的示例。然后,相同的解释将被应用到输入字符串上。

time.Parse函数期望它的layout参数表示一个固定的示例日期。所以,为了解析日期Sun, 03 Jan 2016 10:00:07 CET,适当的示例布局字符串应该是Mon, 02 Jan 2006 15:04:05 MST

layout := "Mon, 02 Jan 2006 15:04:05 MST"
t, err := time.Parse(layout, "Sun, 03 Jan 2016 10:00:07 CET")
if err != nil {
    // 适当处理错误!
}

fmt.Println(t)
英文:

First of all: You're silently ignoring the error this is returned as second return value of time.Parse. I'd suggest handling the error appropriately, instead.

Secondly, let's have a look at the documentation of time.Parse:

>Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

The time.Parse function expects its layout parameter to represent a fixed example date. So, in order to parse the date Sun, 03 Jan 2016 10:00:07 CET, the appropriate example layout string should be Mon, 02 Jan 2006 15:04:05 MST:

layout := "Mon, 02 Jan 2006 15:04:05 MST"
t, err := time.Parse(layout, "Sun, 03 Jan 2016 10:00:07 CET")
if err != nil {
    // handle the error somehow!
}

fmt.Println(t)

huangapple
  • 本文由 发表于 2016年1月3日 17:03:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/34574891.html
匿名

发表评论

匿名网友

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

确定