我尝试在Go中解析日期字符串“2014-09-12T11:45:26.371Z”。此时间格式定义为:

rfc - 3339日期-时间 iso - 8601日期-时间

Code

layout := "2014-09-12T11:45:26.371Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout , str)

我得到了这个错误:

解析时间“2014-11-12T11:47:39.489Z”:月份超出范围

我如何解析这个日期字符串?


当前回答

我会建议利用时间。RFC3339常量从时间包。您可以从time包中检查其他常数。 https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}

其他回答

如果您使用过其他语言中的时间/日期格式化/解析,您可能已经注意到其他语言使用特殊的占位符进行时间/日期格式化。例如ruby语言使用

%d for day
%Y for year

等。Golang并没有像上面那样使用代码,而是使用日期和时间格式占位符,看起来只像日期和时间。Go使用标准时间,即:

Mon Jan 2 15:04:05 MST 2006  (MST is GMT-0700)
or 
01/02 03:04:05PM '06 -0700

如果你注意到Go使用

01 for the day of the month,
02 for the month
03 for hours,
04 for minutes
05 for second
and so on

因此,例如解析2020-01-29,布局字符串应该是06-01-02或2006-01-02。

您可以在这个链接(https://golangbyexample.com/parse-time-in-golang/)上查看完整的占位符布局表

使用这里描述的精确布局数字和一个漂亮的博客。

so:

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

给:

>> 2014-11-12 11:45:26.371 +0000 UTC

我知道。不可思议。也第一次抓住了我。 Go只是没有为datetime组件使用抽象语法(YYYY-MM-DD),但是这些确切的数字(我认为Go第一次提交的时间是不,根据这个。有人知道吗?)

对于那些遇到这种情况的人,利用好时间。RFC3339相对于字符串常量“2006-01-02T15:04:05.000Z”。原因如下:

regDate := "2007-10-09T22:50:01.23Z"

layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)

if err != nil {
    fmt.Println("Static format doesn't work")
} else {
    fmt.Println(t1)
}

layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)

if err != nil {
    fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
    fmt.Println(t2)
}

这将产生以下结果:

Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC

这是游乐场通

使用的布局确实是“2006-01-02T15:04:05.000Z”在RickyA的回答中描述的。 它不是“第一次提交围棋的时间”,而是一种记住所述布局的助记方法。 看到包裹/时间:

布局中使用的参考时间为:

Mon Jan 2 15:04:05 MST 2006

即Unix时间1136239445。 由于MST为GMT-0700,所以参考时间可以认为为

 01/02 03:04:05PM '06 -0700

(1、2、3、4、5、6、7,只要你记得1代表月,2代表日,这对像我这样的欧洲人来说并不容易,因为我习惯了日-月的日期格式)

如“时间”所示。解析:为什么golang解析时间不正确?”,这种布局(使用1、2、3、4、5、6、7)必须完全遵守。

我会建议利用时间。RFC3339常量从时间包。您可以从time包中检查其他常数。 https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}