在Go语言中获取Unix时间戳(自纪元以来的当前时间,以秒为单位)

huangapple go评论97阅读模式
英文:

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

问题

我有一些用Go语言编写的代码,我正在尝试更新它以适应最新的每周构建版本。(它是在r60下构建的)。除了以下部分之外,现在一切都正常工作:

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

有关如何更新此代码以适应当前的Go实现的任何建议吗?

英文:

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

得分: 224

port[5] = time.Now().Unix()

英文:
import "time"
...
port[5] = time.Now().Unix()

答案2

得分: 51

如果你想将它作为string,只需通过strconv进行转换:

package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	timestamp := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
	fmt.Println(timestamp) // 输出:1436773875771421417
}
英文:

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

得分: 18

另一个提示。time.Now().UnixNano()(godoc)将给出自纪元以来的纳秒数。它不严格遵循Unix时间,但它使用相同的纪元给出了亚秒精度,这可能很方便。

编辑:更改以匹配当前的golang api

英文:

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

答案4

得分: 2

根据这里另一个答案的想法,为了得到一个可读的解释,你可以使用:

package main

import (
    "fmt"
    "time"
)

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

Go Playground中尝试一下。

英文:

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.

huangapple
  • 本文由 发表于 2012年3月3日 03:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/9539108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定