2014-09-20 61 views
1

是否有在一個RFC時間戳轉換爲Unix時間所包括的庫的存儲庫或功能(或另一種格式,然後我可以格式化爲Unix時間?)golang RFC2822轉換

例如,我想將此Tue Sep 16 21:58:58 +0000 2014更改爲Unix時間戳。

回答

4

例如,

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. Date and Time Specification

注:

有一個包time格式常量名爲RubyDate;這是一個誤用。

The 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使用的日期格式。在開始的時候,在「失敗鯨魚」日子裏,Twitter使用了Ruby-on-Rails,這可能是他們認爲它是Ruby日期格式的原因。

我沒有在我的例子中使用time.RubyDate常數,因爲它是誤導性的。一個名爲rfc2822的常量提供了更好的文檔。

參考文獻:

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

Diff of format.go revision 0f80c5e80c0e

Twitter Search is Now 3x Faster

+2

這種形式好像是叫time.RubyDate – 2014-09-20 22:01:42

+0

@ NickCraig木業你能就此展開? golang'time'包中有'time.RubyDate'方法嗎? – bvpx 2014-09-20 22:12:08

+0

@bvpx不是一種方法,而是一種時間格式,具有與上面相同的定義'RubyDate =「Mon Jan 02 15:04:05 -0700 2006」' – 2014-09-20 22:27:34