英文:
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
}
我的疑问是:
time包是否提供了任何可以帮助我优化这段代码的函数?- 我是否应该直接使用
gettimeofday()系统调用? - 尝试实现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
- Is there any functions that 
timepackage exposes that might help
me optimize this - Should i be using gettimeofday() system call directly
 - 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% 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论