简单的时间加法和比较GO

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

Simple Add to time and compare GO

问题

嗨,我似乎无法理解在Go中进行时间运算的正确方法。

我有一个时间“对象”,稍后初始化为Now()并存储。

   insertTime time.Time

稍后,我需要查看该项目是否比15分钟更旧。

我该如何做到这一点?
我需要创建一个Duration为15分钟,将其添加到当前时间并进行比较吗?如果是这样,我该如何做到这一点?

英文:

Hi I can't seem to get my head around the correct way to do time arithmetic in Go.

I have a time "object" later initialized to Now() and stored.

   insertTime time.Time

Later, I need to see if the item is older than 15 minutes.

How do i do this?
Do I need to create a Duration of 15 Minutes add it to the current time and compare? If so, how do I do that?

答案1

得分: 8

func (Time) After将会很有帮助,我相信。模式:

when := time.Now()

...

if time.Now().After(when.Add(15*time.Minute)) {
        // 如果至少过去了15分钟,则有条件地处理某些事情
}

when可以是某个结构体的字段,而不是一个变量,例如。

另一种方法:

deadline := time.Now().Add(15*time.Minute)

...

if time.Now().After(deadline) {
        // 如果至少过去了15分钟,则有条件地处理某些事情
}

我个人更喜欢后一种版本。

英文:

func (Time) After will be helpful, I believe. Schema:

when := time.Now()

...

if time.Now().After(when.Add(15*time.Minute)) {
        // Conditionally process something if at least 15 minutes elapsed
}

Instead of a variable, when could be a field of some struct, for example.

Alternative approach:

deadline := time.Now().Add(15*time.Minute)

...

if time.Now().After(deadline) {
        // Conditionally process something if at least 15 minutes elapsed
}

I prefer the later version personally.

huangapple
  • 本文由 发表于 2013年3月13日 21:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/15386741.html
匿名

发表评论

匿名网友

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

确定