Compare time in Go

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

Compare time in Go

问题

我有一个包含列created_at的表,我需要将该列中的时间与当前时间进行比较,例如:

result := database.DB.Where("code = ?", post.code).First(&post)

if result.CreatedAt.Before(time.Now()) {
    // 进行某些操作
}

我在编辑器中遇到错误:Invalid operation: result.CreatedAt > time.Now() (the operator > is not defined on Time)(无效操作:result.CreatedAt > time.Now()(Time类型上未定义操作符>))

如何检查日期是否过期?

英文:

I have a table contains column created_at I need to compare the time in this column with the now time for example:


result := database.DB.Where("code = ?", post.code).First(&post)

if result.CreatedAt < time.Now() {
		// do something
}

I got error in my editor: Invalid operation: result.CreatedAt > time.Now() (the operator > is not defined on Time)

How can check if the date expires?

答案1

得分: 3

使用time.Aftertime.Before函数。

Playground示例:

package main

import (
    "fmt"
    "time"
)

func main() {
    created := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
    now := time.Now()
    if created.Before(now) {
        fmt.Println("做一些事情")
    }
}
英文:

By using time.After or time.Before.

Playground example:

package main

import (
    "fmt"
    "time"
)

func main() {
    created := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
    now := time.Now()
    if created.Before(now) {
        fmt.Println("do something")
    }
}

huangapple
  • 本文由 发表于 2021年10月6日 21:42:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/69466923.html
匿名

发表评论

匿名网友

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

确定