我想为第二天(明天)的确切时间点创建一个 time.Time
。现在我想设置小时和分钟。
这是我目前使用的代码:
now := time.Now()
tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 15, 0, 0, 0, time.UTC).AddDate(0,0,1)
这将为今天创建一个包含我正在寻找的确切时间(小时和分钟)的 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)
我使用 AddDate(0, 0, 1)
向这个日期添加了一天。结果就是第二天所需的时间:2009-11-11 15:00:00 +0000 UTC
。
参见:https://play.golang.org/p/OKR9V1HN50x
问题:
有没有更短的方法来编写这段代码?
最佳答案
import "time"
The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 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)
}
输出:
2019-06-21 16:23:06.525478162 -0400 EDT
2019-06-22 15:00:00 -0400 EDT
一些基准:
BenchmarkNow-8 31197811 36.6 ns/op
BenchmarkTomorrowPeterSO-8 29852671 38.4 ns/op
BenchmarkTomorrowJens-8 9523422 124 ns/op
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
}
}
关于go - 如何获取第二天的具体时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709585/