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

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

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义