在Rails的`where`查询中格式化日期。

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

Format date in where query of rails

问题

I wanted to know that is there any way to format the date in where query for particular column.
I have a mongo record which has one column called start_date which is stored in string like this: "20221104". I need this start_date to be formatted like "2022-11-04" in where query.

One way I know is to iterate over the query result and format the date. I'm looking if there is any other way to achieve this.

result = Subscription.where(state: "active")
英文:

I wanted to know that is there any way to format the date in where query for particular column.
I have a mongo record which has one column called start_date which is stored in string like this: "20221104". I need this start_date to be formatted like "2022-11-04" in where query.

One way I know is to iterate over the query result and format the date. I'm looking if there is any other way to achieve this.

result = Subscription.where(state: "active")

答案1

得分: 7

我认为你可以将 "start_date" 与输入日期对象的字符串表示形式在 where 查询中进行比较。

result = Subscription.where(start_date: date.strftime("%Y%m%d"))

你可以访问这里获取更多详细信息。

英文:

I think you can compare "start_date" to string representation of an input date object in where query.

result = Subscription.where(start_date: date.strftime("%Y%m%d"))

You can visit here for more details.

huangapple
  • 本文由 发表于 2023年5月23日 00:07:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308055.html
匿名

发表评论

匿名网友

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

确定