douwan2664 2016-02-28 21:20
浏览 1372
已采纳

如何使用Golang将UTC时间转换为Unix时间戳

I am looking for an option to convert UTC time string to unix timestamp.

The string variable I have is 02/28/2016 10:03:46 PM and it needs to be converted to a unix timestamp like 1456693426

Any idea how to do that?

  • 写回答

1条回答 默认 最新

  • dsds33222 2016-02-28 22:58
    关注

    First of, the unix timestamp 1456693426 does not have the time 10:03:46 PM but 9:03:46 PM in UTC.

    In the time package there is the function Parse with expects a layout to parse the time. The layout is constructed from the reference time Mon Jan 2 15:04:05 -0700 MST 2006. So in your case the layout would be 01/02/2006 3:04:05 PM. After using Parse you get a time.Time struct on which you can call Unix to receive the unix timestamp.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        layout := "01/02/2006 3:04:05 PM"
        t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(t.Unix())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。