golang RFC2822 转换

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

golang RFC2822 conversion

问题

在包含的库中是否有一个将RFC时间戳转换为Unix时间(或其他格式,然后可以将其格式化为Unix时间)的库或函数?

例如,我想将Tue Sep 16 21:58:58 +0000 2014转换为Unix时间戳。

英文:

Is there a library or function in the included libraries that converts an RFC timestamp to Unix time (or another format that I can then format into Unix time?)

For example, I'd like to change this Tue Sep 16 21:58:58 +0000 2014 to a Unix timestamp.

答案1

得分: 7

例如,

package main

import (
	"fmt"
	"time"
)

func main() {
	s := "Tue Sep 16 21:58:58 +0000 2014"
	const rfc2822 = "Mon Jan 02 15:04:05 -0700 2006"
	t, err := time.Parse(rfc2822, s)
	if err != nil {
		fmt.Println(err)
		return
	}
	u := t.Unix()
	fmt.Println(u)
	f := t.Format(time.UnixDate)
	fmt.Println(f)
}

输出:

1410904738
Tue Sep 16 21:58:58 +0000 2014

参考资料:

Package time

RFC2822: 3.3. 日期和时间规范

注意:

有一个名为time的包中的格式常量名为RubyDate,这是一个误导。

Go的作者被Go Issue 518误导,该问题声称Ruby的Time.now输出为Tue Jan 12 02:52:59 -0800 2010。然而,

#!/usr/bin/env ruby
print Time.now
print "\n"

输出:

2014-09-20 19:40:32 -0400

后来,该问题被修改为Tue Jan 12 02:52:59 -0800 2010是Twitter API使用的日期格式。在最初的“Fail Whale”时期,Twitter使用的是Ruby-on-Rails,这可能是他们认为这是Ruby日期格式的原因。

我在示例中没有使用time.RubyDate常量,因为它会产生误导。一个名为rfc2822的常量提供了更好的文档。

参考资料:

Go: Issue 518: time.Parse - numeric time zones and spacing

format.go修订版本0f80c5e80c0e的差异

Twitter Search现在快了3倍

英文:

For example,

package main

import (
	"fmt"
	"time"
)

func main() {
	s := "Tue Sep 16 21:58:58 +0000 2014"
	const rfc2822 = "Mon Jan 02 15:04:05 -0700 2006"
	t, err := time.Parse(rfc2822, s)
	if err != nil {
		fmt.Println(err)
		return
	}
	u := t.Unix()
	fmt.Println(u)
	f := t.Format(time.UnixDate)
	fmt.Println(f)
}

Output:

1410904738
Tue Sep 16 21:58:58 +0000 2014

References:

Package time

RFC2822: 3.3. Date and Time Specification

NOTE:

There is a package time format constant named RubyDate; it's a misnomer.

The Go authors were misled by Go Issue 518 which claimed that Ruby Time.now outputs Tue Jan 12 02:52:59 -0800 2010. However,

#!/usr/bin/env ruby
print Time.now
print "\n"

Output:

2014-09-20 19:40:32 -0400

Later, the issue was revised to say that Tue Jan 12 02:52:59 -0800 2010 was the date format used by the Twitter API. In the beginning, in the "Fail Whale" days, Twitter used Ruby-on-Rails, which may be why they assumed it was a Ruby date format.

I didn't use the time.RubyDate constant in my example since it's misleading. A constant named rfc2822 provides better documentation.

References:

Go: Issue 518: time.Parse - numeric time zones and spacing

Diff of format.go revision 0f80c5e80c0e

Twitter Search is Now 3x Faster

huangapple
  • 本文由 发表于 2014年9月21日 04:48:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/25953158.html
匿名

发表评论

匿名网友

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

确定