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

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

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

问题

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

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

我的疑问是:

  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

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

Code

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

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

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Print(MinutesToTime(780).UTC())
}

func MinutesToTime(m int64) time.Time {
	return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
}
% go run test.go
2017-01-29 13:00:00 +0000 UTC%
package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Print(MinutesToTime(780).UTC())
}

func MinutesToTime(m int64) time.Time {
	return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
}
% go run test.go
2017-01-29 13:00:00 +0000 UTC%
英文:
package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Print(MinutesToTime(780).UTC())
}

func MinutesToTime(m int64) time.Time {
	return time.Unix(time.Now().Unix()/86400*86400+m*60, 0)
}

% go run test.go                                                                                                         
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:

确定