Unix时间在GOLANG中返回0或一些小值。

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

Unix time returns 0 or some small value in GOLANG

问题

以下是翻译好的内容:

下面的GO代码有什么问题?我尝试了一个GO项目,并在Openshift上部署,一切都很好,直到昨天。突然从今天开始,time包返回0。

val,_ := strconv.ParseInt(string(time.Now().Unix()),10,64)
println("Time now in openshift :",time.Now().Second())

所以基本上这里的实际时间是"1969-12-31"。可能是GO中的一个错误。

英文:

What is wrong with the below GO code? I tried a GO project and deployed in Openshift and everything was fine till yesterday. All of a sudden from today, the time package returns 0

val,_ := strconv.ParseInt(string(time.Now().Unix()),10,64)
println("Time now in openshift :",time.Now().Second())

So basically actual time here is "1969-12-31". Could be the bug in GO.

答案1

得分: 5

没有必要手动将时间转换为字符串,time.Format会为您完成这个任务。或者,如果您想打印自纪元以来的秒数,可以简单地使用%d占位符,该占位符专门用于打印十进制数字。以下是示例代码:

package main

import "fmt"
import "time"

func main() {
    fmt.Printf("Hello, %s\n", time.Now().Format(time.RFC3339))
    fmt.Printf("Seconds since epoch %d", time.Now().Unix())
}

您可以在playground上运行此代码。

英文:

There is absolutely no need to convert the time to a string by hand, time.Format does this for you. Or, if you want to print out the seconds since epoch, simply use the %d verb, which is explicitly for printing base10 decimal numbers <kbd>Run on playground</kbd>

package main

import &quot;fmt&quot;
import &quot;time&quot;

func main() {
    fmt.Printf(&quot;Hello, %s\n&quot;,time.Now().Format(time.RFC3339))
	fmt.Printf(&quot;Seconds since epoch %d&quot;,time.Now().Unix())
}

答案2

得分: 2

首先,为什么你在Unix已经返回int64的情况下还要使用strconv呢?

其次,string(int)转换并不是你想的那样。它在Unicode码点(也称为rune)和字符串之间进行转换。在这里你需要使用strconv.Itoa

val, _ := strconv.ParseInt(strconv.FormatInt(time.Now().Unix(), 10), 10, 64)
println("Time now in openshift :", val)

http://play.golang.org/p/AC7Q84ZIMC

英文:

First of all, why are you using strconv if Unix already returns an int64?

Secondly, string(int) conversion doesn't do what you think it does. It converts between Unicode code points (aka runes) and strings. You need strconv.Itoa here:

val, _ := strconv.ParseInt(strconv.FormatInt(time.Now().Unix(), 10), 10, 64)
println(&quot;Time now in openshift :&quot;, val)

http://play.golang.org/p/AC7Q84ZIMC

huangapple
  • 本文由 发表于 2016年2月11日 00:11:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/35320251.html
匿名

发表评论

匿名网友

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

确定