Golang日期解析

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

Golang date parsing

问题

我有一个像这样的字符串:

Fri, 3 Mar 2017 13:08:54 +0100

我需要将这个字符串转换为 Golang 中的 time.Time 对象。

这个字符串的格式似乎是 RFC1123Z,所以我尝试了以下方式:

(RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone)

d := "Thu, 2 Mar 2017 10:44:13 +0100"
da, _ := time.Parse(time.RFC1123Z, d)
fmt.Println(da)

但是我得到了这个结果:

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

出了什么问题?

英文:

I have a string like this

Fri, 3 Mar 2017 13:08:54 +0100

I need to convert this string in a time.Time object in Golang.

The layout seems to be RFC1123Z so I have try in this way

(RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone)

d := "Thu, 2 Mar 2017 10:44:13 +0100"
da, _ := time.Parse(time.RFC1123Z, d)
fmt.Println(da)

But I get this:

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

What is wrong?

答案1

得分: 1

对于time.RFC1123Z来说,日期必须是02而不是2

package main

import (
	"fmt"
	"time"
)

func main() {
	d := "Thu, 02 Mar 2017 10:44:13 +0100"
	da, _ := time.Parse(time.RFC1123Z, d)
	fmt.Println(da)
}

如果你不能改变源时间字符串,你可以使用Mon, 2 Jan 2006 15:04:05 -0700格式进行解析:

da, _ := time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", d)

参考资料:

英文:

For it to be time.RFC1123Z the day must be 02 not 2.

package main

import (
	"fmt"
	"time"
)

func main() {
	d := "Thu, 02 Mar 2017 10:44:13 +0100"
	da, _ := time.Parse(time.RFC1123Z, d)
	fmt.Println(da)
}

https://play.golang.org/p/JFtErfZTtk

If you cannot change the source time string you can alternatively parse it with the Mon, 2 Jan 2006 15:04:05 -0700 format:

da, _ := time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", d)

References:

答案2

得分: 0

请尝试以下代码:

func ParseRFC1123Z(date string) (t time.Time, err error) {
    t, err = time.Parse(time.RFC1123Z, date)
    errOriginal := err
    if err != nil {
        t, err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", date)
    }
    if err != nil {
        err = errOriginal
    }
    return
}

你可以在这个链接中查看代码的运行结果:https://go.dev/play/p/LwYRTBsM4KU

英文:

Try this

func ParseRFC1123Z(date string) (t time.Time, err error) {
	t, err = time.Parse(time.RFC1123Z, date)
	errOriginal := err
	if err != nil {
		t, err = time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", date)
	}
	if err != nil {
		err = errOriginal
	}
	return 
}

https://go.dev/play/p/LwYRTBsM4KU

huangapple
  • 本文由 发表于 2017年7月13日 15:47:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/45074481.html
匿名

发表评论

匿名网友

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

确定