英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论