doujia2386 2014-09-20 20:48
浏览 75
已采纳

golang RFC2822转换

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条回答 默认 最新

  • drvvepadi289421028 2014-09-20 21:04
    关注

    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 "
    "
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?