英文:
Compare SQL date column with date
问题
假设我将日期列的值插入为:
TO_DATE('06/08/2021', 'DD/MM/YYYY')
我想在 Golang 中将此列 valid_till
进行比较,代码如下:
_err := database.GetDbReadClient().Raw("SELECT * from base_configs WHERE tenant = ? AND valid_till <= ?", tenant, time.Now()).Scan(&baseConfig).Error
time.Now()
无法工作。但是我不知道如何比较日期。
我的在 Postgres 中的插入是否正确?
如果正确,我应该用什么来替代 time.Now()
来与 valid_till
列进行比较?
英文:
Suppose I inserted the date column value as
TO_DATE('06/08/2021', 'DD/MM/YYYY')
I want to compare this column valid_till
in Golang as
_err := database.GetDbReadClient().Raw("SELECT * from base_configs WHERE tenant = ? AND valid_till <= ?", tenant, time.Now()).Scan(&baseConfig).Error
time.Now()
won't work. But I am not getting around how to go about it to compare dates.
Is my insertion in Postgres correct?
If so, what can I write instead of time.Now to compare it with valid_till
column?
答案1
得分: 1
你可以将参数转换为原始 SQL 中的 date
类型。
raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?::date`
err := database.GetDbReadClient().Raw(raw, tenant, time.Now()).Scan(&baseConfig).Error
或者将 time.Time
实例格式化为日期字符串。
raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?`
date := time.Now().Format("02/01/2006")
err := database.GetDbReadClient().Raw(raw, tenant, date).Scan(&baseConfig).Error
英文:
You could cast the parameter to the date
type in the raw SQL.
raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?::date`
err := database.GetDbReadClient().Raw(raw, tenant, time.Now()).Scan(&baseConfig).Error
Or just format the time.Time
instance as a date string
.
raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?`
date := time.Now().Format("02/01/2006")
err := database.GetDbReadClient().Raw(raw, tenant, date).Scan(&baseConfig).Error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论