How do I get the time one day ago relative to the current?

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

How do I get the time one day ago relative to the current?

问题

我需要查询我的数据库以获取在一个小时内发生的事件。因此,我想获取现在之前(即现在-24小时,或现在-1天)之间的事件。

我尝试了这种方法,但是不正确 -

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. now := time.Now()
  8. // 打印当前时间
  9. fmt.Println(now)
  10. then := time.Now()
  11. diff := 24
  12. diff = diff.Hours()
  13. then = then.Add(-diff)
  14. // 打印24小时前的时间
  15. fmt.Println(then)
  16. // 打印'now'和'then'之间的时间差
  17. fmt.Println(now.Sub(then))
  18. }

如何使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 -

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. now := time.Now()
  8. // print the time now
  9. fmt.Println(now)
  10. then := time.Now()
  11. diff := 24
  12. diff = diff.Hours()
  13. then = then.Add(-diff)
  14. // print the time before 24 hours
  15. fmt.Println(then)
  16. // print the delta between 'now' and 'then'
  17. fmt.Println(now.Sub(then))
  18. }

How can I make then == 1 full day / 24 hours before now ?

Thanks a lot for your help!!

答案1

得分: 7

使用时间包中提供的Duration常量,例如time.Hour

  1. diff := 24 * time.Hour
  2. then := time.Now().Add(-diff)

或者如果你想要前一天的同一时间(可能不是提前24小时,http://play.golang.org/p/B32RbtUuuS)。

  1. then := time.Now().AddDate(0, 0, -1)
英文:

Use the Duration constants provided in the time package, like time.Hour

  1. diff := 24 * time.Hour
  2. 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)

  1. then := time.Now().AddDate(0, 0, -1)

huangapple
  • 本文由 发表于 2016年4月13日 01:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/36580014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定