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

折月煮酒 提交于 2019-12-29 13:39:14

问题


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 following bit:

 if t, _, err := os.Time(); err == nil {
   port[5] = int32(t)
 }

Any advice on how to update this to work with the current Go implementation?


回答1:


import "time"
...
port[5] = int32(time.Now().Unix())



回答2:


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
}



回答3:


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



来源:https://stackoverflow.com/questions/9539108/obtaining-a-unix-timestamp-in-go-language-current-time-in-seconds-since-epoch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!