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

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

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)

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:

确定