Obtaining a Unix Timestamp in Go Language (current time in seconds since epoch)

前端 未结 4 593
既然无缘
既然无缘 2020-12-13 05:30

I have some code written in Go which I am trying to update to work with the latest weekly builds. (It was last built under r60). Everything is now working except for the fol

相关标签:
4条回答
  • 2020-12-13 05:52

    Building on the idea from another answer here, to get a human-readable interpretation, you can use:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        timestamp := time.Unix(time.Now().Unix(), 0)
        fmt.Printf("%v", timestamp) // prints: 2009-11-10 23:00:00 +0000 UTC
    }
    

    Try it in The Go Playground.

    0 讨论(0)
  • 2020-12-13 05:54

    Another tip. time.Now().UnixNano()(godoc) will give you nanoseconds since the epoch. It's not strictly Unix time, but it gives you sub second precision using the same epoch, which can be handy.

    Edit: Changed to match current golang api

    0 讨论(0)
  • 2020-12-13 06:01

    If you want it as string just convert it via strconv:

    package main
    
    import (
        "fmt"
        "strconv"
        "time"
    )
    
    func main() {
        timestamp := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
        fmt.Println(timestamp) // prints: 1436773875771421417
    }
    
    0 讨论(0)
  • 2020-12-13 06:04
    import "time"
    ...
    port[5] = int32(time.Now().Unix())
    
    0 讨论(0)
提交回复
热议问题