英文:
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 "fmt"
import "time"
func main() {
fmt.Printf("Hello, %s\n",time.Now().Format(time.RFC3339))
fmt.Printf("Seconds since epoch %d",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 rune
s) and strings. You need strconv.Itoa
here:
val, _ := strconv.ParseInt(strconv.FormatInt(time.Now().Unix(), 10), 10, 64)
println("Time now in openshift :", val)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论