我想为time.Time第二天(明天)的确切时间点创建一个。现在我想设置小时和分钟。
这是我目前使用的代码:
now := time.Now()
tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, time.UTC).AddDate(0,0,1)
Run Code Online (Sandbox Code Playgroud)
这将为Date今天创建一个我正在寻找的确切时间(小时和分钟),然后添加一天Date。这工作正常。
例子:
试想一下time.Now()就是2009-11-10 23:00:00 +0000 UTC。
以下代码的结果将是: 2009-11-10 15:00:00 +0000 UTC
tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, time.UTC)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我使用AddDate(0, 0, 1). 结果是第二天所需的时间:2009-11-11 15:00:00 +0000 UTC。
参见:https : //play.golang.org/p/OKR9V1HN50x
题:
有没有更短的方法来编写这段代码?
Run Code Online (Sandbox Code Playgroud)import "time"月、日、小时、分钟、秒和 nsec 值可能超出其通常范围,并将在转换过程中进行标准化。例如,10 月 32 日转换为 11 月 1 日。
这样效率更高。它最大限度地减少了对包time函数和方法的调用。
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now.Round(0))
yyyy, mm, dd := now.Date()
tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location())
fmt.Println(tomorrow)
}
Run Code Online (Sandbox Code Playgroud)
输出:
2019-06-21 16:23:06.525478162 -0400 EDT
2019-06-22 15:00:00 -0400 EDT
Run Code Online (Sandbox Code Playgroud)
一些基准:
BenchmarkNow-8 31197811 36.6 ns/op
BenchmarkTomorrowPeterSO-8 29852671 38.4 ns/op
BenchmarkTomorrowJens-8 9523422 124 ns/op
Run Code Online (Sandbox Code Playgroud)
bench_test.go:
package main
import (
"testing"
"time"
)
func BenchmarkNow(b *testing.B) {
for N := 0; N < b.N; N++ {
now := time.Now()
_ = now
}
}
var now = time.Now()
func BenchmarkTomorrowPeterSO(b *testing.B) {
for N := 0; N < b.N; N++ {
// now := time.Now()
yyyy, mm, dd := now.Date()
tomorrow := time.Date(yyyy, mm, dd+1, 15, 0, 0, 0, now.Location())
_ = tomorrow
}
}
func BenchmarkTomorrowJens(b *testing.B) {
for N := 0; N < b.N; N++ {
// now := time.Now()
tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, now.Location()).AddDate(0, 0, 1)
_ = tomorrow
}
}
Run Code Online (Sandbox Code Playgroud)