为什么 Date.yesterday 也算作 Date.today? [英] Why does Date.yesterday counts as Date.today also?
问题描述
我有以下模型和方法:
class UserPrice < ActiveRecord::Base
attr_accessible :price, :purchase_date,
def self.today
where(:purchase_date => Date.today)
end
def self.yesterday
where(:purchase_date => Date.yesterday)
end
为什么在我的表单上,如果我给我的 date_select 字段 :purchase_date
1/4/2012(yesterday
方法)它也算作今天(today
代码>方法),如果我给它 1/5/2012(今天)它是零?
Why on my form if I give my date_select field :purchase_date
1/4/2012(yesterday
method) it also counts as today(today
method) and if I give it 1/5/2012 (today) it is nil?
附言我在 PostgreSQL 中使用 Rails 3.0.10
.
P.S. I am using Rails 3.0.10
with PostgreSQL.
更新
这是我的控制台返回:
$ rails console --s
Loading development environment in sandbox (Rails 3.0.10)
Any modifications you make will be rolled back on exit
irb(main):001:0> Date.today
=> Wed, 04 Jan 2012
irb(main):002:0> Time.now
=> 2012-01-04 21:28:07 -0500
irb(main):003:0> Time.zone.now
=> Thu, 05 Jan 2012 02:28:18 UTC +00:00
irb(main):004:0> Date.yesterday
=> Wed, 04 Jan 2012
irb(main):005:0>
现在 yesterday
搞砸了,没有意义....
Now yesterday
is screwed up, makes no sense....
推荐答案
这是因为calculation.rb 正在为配置的时区(默认为UTC)调用Date 类的当前"方法.
This is happening because calculations.rb is calling the "current" method of the Date class for the configured timezone (Defaults to UTC).
如果您打开 rails 控制台,您可以通过执行以下操作看到Date.yesterday"正在计算的日期:
If you open the rails console you can see the date at which "Date.yesterday" is calculating on by doing:
Time.zone.today
这可能会显示明天的日期.所以 Rails 眼中的 Date.yesterday 就是今天.;)
This will probably show you tomorrow's date. So Date.yesterday for what rails sees as today, is today. ;)
您可以通过以下方式更直接地使用日期库:
You can work with the Date library more directly by doing:
Date.today.advance(:days => -1)
这会给你昨天的日期,就像你期望的那样,而 active_support 正在返回:
This will give you yesterday's date like you expect whereas active_support is returning:
Date.current.advance(:days => -1)
这篇关于为什么 Date.yesterday 也算作 Date.today?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!