比较 Rails 中的日期
假设我有一个标准的 Post.first.created_at
日期时间。 我可以通过执行以下操作直接将其与 2009-06-03 16:57:45.608000 -04:00
格式的日期时间进行比较:
Post.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
编辑: 两个字段都是 < strong>日期时间,不是日期。
Suppose I have a standard Post.first.created_at
datetime. Can I compare that directly with a datetime in the format 2009-06-03 16:57:45.608000 -04:00
by doing something like:
Post.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
Edit: Both fields are datetimes, not dates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以使用比较运算符来比较日期,例如:
但是您是否尝试将日期与日期时间进行比较?
如果是这种情况,您需要将日期时间转换为日期,然后进行比较。
我希望这有帮助。
Yes, you can use comparison operators to compare dates e.g.:
But are you trying to compare a date to a datetime?
If that's the case, you'll want to convert the datetime to a date then do the comparison.
I hope this helps.
是的,您可以直接将
created_at
ActiveRecord 日期/时间字段的值与常规DateTime
对象(就像您可以通过解析字符串获得的对象)进行比较。在一个项目中,我有一个 Value 对象,它有一个created_at日期时间对象:
created_at字段定义为:
注意,如果您的字段是日期而不是日期时间,那么您需要将其转换为时间:
或解析日期:
否则你会得到一个:
Yes you can compare directly the value of a
created_at
ActiveRecord date/time field with a regularDateTime
object (like the one you can obtain parsing the string you have).In a project i have a Value object that has a created_at datetime object:
The created_at field is defined as:
N.B. if your field is a date and not a datetime, then you need to convert it to a time:
or parse a date:
otherwise you'll get a: