Ruby-on-rails 比较 rails 中的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/992431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:21:17  来源:igfitidea点击:

Comparing dates in rails

ruby-on-railsdatetimedate-math

提问by Tom Lehman

Suppose I have a standard Post.first.created_atdatetime. Can I compare that directly with a datetime in the format 2009-06-03 16:57:45.608000 -04:00by doing something like:

假设我有一个标准的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")

Edit:Both fields are datetimes, not dates.

编辑:两个字段都是datetimes而不是 date

回答by mechanical_meat

Yes, you can use comparison operators to compare dates e.g.:

是的,您可以使用比较运算符来比较日期,例如:

irb(main):018:0> yesterday = Date.new(2009,6,13)
=> #<Date: 4909991/2,0,2299161>
irb(main):019:0> Date.today > yesterday
=> true

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.

我希望这有帮助。

回答by LucaM

Yes you can compare directly the value of a created_atActiveRecord date/time field with a regular DateTimeobject (like the one you can obtain parsing the string you have).

是的,您可以直接将created_atActiveRecord 日期/时间字段的值与常规DateTime对象进行比较(就像您可以通过解析您拥有的字符串获得的对象)。

In a project i have a Value object that has a created_at datetime object:

在一个项目中,我有一个 Value 对象,它有一个 created_at 日期时间对象:

imac:trunk luca$ script/console
Loading development environment (Rails 2.3.2)
>> Value.first.created_at
=> Fri, 12 Jun 2009 08:00:45 CEST 02:00
>> Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> Wed Jun 03 22:57:45 0200 2009
>> Value.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> true

The created_at field is defined as:

created_at 字段定义为:

  create_table "values", :force => true do |t|
    [...]
    t.datetime "created_at"
  end

N.B. if your field is a date and not a datetime, then you need to convert it to a time:

注意,如果您的字段是日期而不是日期时间,那么您需要将其转换为时间:

Post.first.created_at.to_time > Time.parse("2009-06-03 16:57:45.608000 -04:00")

or parse a date:

或解析日期:

Post.first.created_at > Date.parse("2009-06-03 16:57:45.608000 -04:00")

otherwise you'll get a:

否则你会得到一个:

ArgumentError: comparison of Date with Time failed