Go: why does time.Now().Hour/Minute/Second return a six digit number?

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

Go: why does time.Now().Hour/Minute/Second return a six digit number?

问题

我正在学习如何使用Go编程,并尝试创建一个简单的提醒功能。

我想要将当前时间显示为24小时制的格式,XX.XX(小时,分钟)。

我已经将当前时间保存在变量t中,当我打印它时,我发现时间是2009年11月初的23.00。没问题,但是当我打印t.Hour和t.Minute时,结果是132288.132480

当我打印t.Seconds时,结果也类似。我一直没有弄清楚为什么会出现这种情况。

大约过去了2000天,但只有48k小时和2880k分钟,所以我的结果中小时和分钟之间的小差异暗示着问题可能是其他原因。

我在Go Playground中运行这段代码。

我的代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    Remind("该吃饭了")
}


func Remind(text string) {
    t := time.Now()
    fmt.Println(t)
    fmt.Printf("现在的时间是 %d.%d: ", t.Hour(), t.Minute())
    fmt.Printf(text)
    fmt.Println()
}

请注意,我只翻译了代码部分,其他内容不包括在内。

英文:

I am learning how to code in Go and trying to create a simple reminder function.

I want to display the current time as a regular 24 hour clock, XX.XX (hours, minutes).

I have saved the current time in a variable t and when I print it I find out that the time is 23.00 early November 2009. Fine, but when I print t.Hour and t.Minute the result is 132288.132480.

It is something similar when I print t.Seconds. I have not been able to figure out why this happens.

Roughly 2000 days have passed since but that is only 48k hours and 2880k minutes so the small difference between the hours and minutes in my result hints that the issue is something else.

I am running the code in the go playground.

My code:

package main

import (
    "fmt"
    "time"
    )

func main() {
    Remind("It's time to eat")
}


func Remind(text string) {
    t := time.Now()
    fmt.Println(t)
    fmt.Printf("The time is %d.%d: ", t.Hour, t.Minute)
    fmt.Printf(text)
    fmt.Println()
}

答案1

得分: 3

你需要调用 t.Hour() 而不是将其作为一个值使用。

在这里查看 time 包的源代码:https://golang.org/src/time/time.go?s=12994:13018#L390

   399	// Hour 返回 t 指定的一天中的小时数,范围为 [0, 23]。
   400	func (t Time) Hour() int {
   401		return int(t.abs()%secondsPerDay) / secondsPerHour
   402	}
   403	

如果有疑问,你可以通过阅读官方的Go包页面中的特定包源代码来快速找到解释。

英文:

You need to call t.Hour() instead of using it as a value.

Check out the source of time package here: https://golang.org/src/time/time.go?s=12994:13018#L390

   399	// Hour returns the hour within the day specified by t, in the range [0, 23].
   400	func (t Time) Hour() int {
   401		return int(t.abs()%secondsPerDay) / secondsPerHour
   402	}
   403	

When in doubt, you can quickly find an explanation by reading specific package source from official go packages page.

huangapple
  • 本文由 发表于 2016年4月3日 18:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/36384490.html
匿名

发表评论

匿名网友

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

确定