如何在Go语言中对时间对象执行“大于或等于”操作?

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

How to do "greater than or equal" operation on time objects in go?

问题

在Go语言中,你可以这样写:

if time.Now().After(expiry) || time.Now().Equal(expiry) {
    // 执行逻辑
}

这样的话,如果当前时间晚于或等于过期时间,就会执行相应的逻辑。使用time.Now().Equal(expiry)可以判断两个时间是否相等。

英文:

How do I write something like this in go?

if time.Now() >= expiry {
}

If I use time.Now().After(expiry), then it is not really the greater than or equal (>=) logic that I am looking for. If I use time.Now().After(expiry) || time.Now() == expiry, then the expression looks long. Is there a "proper" way to do this?

答案1

得分: 11

正确的方式是:

now := time.Now()
if now.After(expiry) || now.Equal(expiry) {
  ...
}

或者

if !time.Now().Before(expiry) {
  ...
}
英文:

The proper way is:

now:=time.Now()
if now.After(expiry) || now.Equal(expiry) {
  ...
}

Or

if !time.Now().Before(expiry) {
  ...
}

huangapple
  • 本文由 发表于 2021年11月3日 09:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/69818655.html
匿名

发表评论

匿名网友

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

确定