英文:
How do I get the time one day ago relative to the current?
问题
我需要查询我的数据库以获取在一个小时内发生的事件。因此,我想获取现在和之前(即现在-24小时,或现在-1天)之间的事件。
我尝试了这种方法,但是不正确 -
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// 打印当前时间
fmt.Println(now)
then := time.Now()
diff := 24
diff = diff.Hours()
then = then.Add(-diff)
// 打印24小时前的时间
fmt.Println(then)
// 打印'now'和'then'之间的时间差
fmt.Println(now.Sub(then))
}
如何使then等于now之前的1天/24小时?
非常感谢你的帮助!
英文:
I need to query my db for events occurred within a single hour.
Therefore, I want to get events between now and then (which is now - 24 hours, or now - 1 full day).
I tried this approach, but it is incorrect -
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// print the time now
fmt.Println(now)
then := time.Now()
diff := 24
diff = diff.Hours()
then = then.Add(-diff)
// print the time before 24 hours
fmt.Println(then)
// print the delta between 'now' and 'then'
fmt.Println(now.Sub(then))
}
How can I make then == 1 full day / 24 hours before now ?
Thanks a lot for your help!!
答案1
得分: 7
使用时间包中提供的Duration常量,例如time.Hour
。
diff := 24 * time.Hour
then := time.Now().Add(-diff)
或者如果你想要前一天的同一时间(可能不是提前24小时,http://play.golang.org/p/B32RbtUuuS)。
then := time.Now().AddDate(0, 0, -1)
英文:
Use the Duration constants provided in the time package, like time.Hour
diff := 24 * time.Hour
then := time.Now().Add(-diff)
Or if you want the same time on the previous day (which may not be 24 hours earlier, http://play.golang.org/p/B32RbtUuuS)
then := time.Now().AddDate(0, 0, -1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论