doushan2311
2016-04-03 10:47 阅读 80
已采纳

转到:为什么time.Now()。Hour / Minute / Second返回六位数?

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条回答 默认 最新

  • 已采纳
    dpvmjk0479 dpvmjk0479 2016-04-03 11:06

    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.

    点赞 评论 复制链接分享

相关推荐