检查DateTime值是今天,明天还是以后

时间:2014-10-26 22:09:08

标签: ruby-on-rails datetime ruby-on-rails-4

我有一个DateTime类的对象属性。

如果保存的日期是今天,明天还是以后,我如何理解?

3 个答案:

答案 0 :(得分:58)

以下是实现它的一些有用方法:

datetime = DateTime.now  => Sun, 26 Oct 2014 21:00:00

datetime.today? # => true
datetime.to_date.past? # => false (only based on date)
datetime.to_date.future? # => false  (only based on date)

datetime.to_date == Date.tomorrow # => false
datetime.to_date == Date.yesterday # => false

答案 1 :(得分:4)

像...一样的东西。

datetime = Time.now.to_datetime
=> Sun, 26 Oct 2014 16:24:55 -0600 

datetime >= Date.today
=> true

datetime < Date.tomorrow
=> true

datetime += 1.day
=> Mon, 27 Oct 2014 16:25:12 -0600

datetime >= Date.today
=> true

datetime >= Date.tomorrow
=> true 

datetime < (Date.tomorrow + 1.day)
=> false

答案 2 :(得分:2)

昨天? &明天? (Rails 6.1 +)

Rails 6.1向Date和Time类添加了新的#yesterday?#tomorrow?方法。

结果,现在,您的问题可以解决为:

datetime = DateTime.current
# => Mon, 16 Nov 2020 20:50:16 +0000


datetime.today?
# => true

datetime.yesterday?
# => false

datetime.tomorrow?
# => false

还值得一提的是,#yesterday?#tomorrow?的别名为#prev_day?#next_day?

这里是a link to the corresponding PR