英文:
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
参考资料:
注意:
有一个名为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
英文:
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:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论