给定当前时间(以分钟为单位),在golang中获取UTC时间的最佳方法是什么?

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

Optimal way to get time in UTC given today's time as minutes in golang

问题

我有一段代码,需要将以分钟为单位的时间(即小时*60+分钟)转换为time.Time类型。以下是我尝试实现的代码。

  1. func MinutesToTime(minutes int) time.Time {
  2. t := time.Now().UTC() // 可以缓存
  3. h, m, _ := t.Clock()
  4. diff := minutes - (h*60 + m)
  5. t = t.Add(time.Duration(diff) * time.Minute)
  6. return t
  7. }

我的疑问是:

  1. time包是否提供了任何可以帮助我优化这段代码的函数?
  2. 我是否应该直接使用gettimeofday()系统调用?
  3. 尝试实现vDSO是否过于复杂?只有amd64架构的vDSO实现可以在Go源代码中找到。

注意:由于分钟是最小的粒度,59秒的误差是可以接受的。

英文:

I have time of the same day in minutes (ie, hours * 60 + minutes) as input ,need to convert it into time.Time here is my attempt to do the same .

Example

  1. Input: 780
  2. Output : 2017-01-29 13:00:51.992871217 +0000 UTC

Code

  1. func MinutesToTime(minutes int) time.Time {
  2. t := time.Now().UTC() //may be cached
  3. h, m, _ := t.Clock()
  4. diff := minutes - (h*60 + m)
  5. t = t.Add(time.Duration(diff) * time.Minute)
  6. return t
  7. }

Doubt

  1. Is there any functions that time package exposes that might help
    me optimize this
  2. Should i be using gettimeofday() system call directly
  3. Would trying to implement vDSO be an overkill , vDSO implementation for only amd64 is found in go source code

PS
The 59 sec err is acceptable as minute is my lowest granularity

答案1

得分: 1

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. fmt.Print(MinutesToTime(780).UTC())
  8. }
  9. func MinutesToTime(m int64) time.Time {
  10. return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
  11. }
  1. % go run test.go
  2. 2017-01-29 13:00:00 +0000 UTC%
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. fmt.Print(MinutesToTime(780).UTC())
  8. }
  9. func MinutesToTime(m int64) time.Time {
  10. return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
  11. }
  1. % go run test.go
  2. 2017-01-29 13:00:00 +0000 UTC%
英文:
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. fmt.Print(MinutesToTime(780).UTC())
  8. }
  9. func MinutesToTime(m int64) time.Time {
  10. return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
  11. }
  12. % go run test.go
  13. 2017-01-29 13:00:00 +0000 UTC%

huangapple
  • 本文由 发表于 2017年1月29日 16:15:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/41918897.html
匿名

发表评论

匿名网友

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

确定