在时区找到的Rails - 不工作 [英] Rails in time zone finding - not working
问题描述
我有 CarRoute id:22783,route_time:2016-07-07 05:30 :00
,但在 CarRoute.find_by_id(22783).route_time是星期四,07七月2016 07:30:00 CEST +02:00
所以rails添加2h,但是当我想要通过时间找到此路由不起作用时,
CarRoute.where(:id => 22783,:route_time => DateTime.new(Date.today.year,Date.today.month,Date.today.day,7,0 ,0,0).. DateTime.new(Date.today.year,Date.today.month,Date.today.day,19,0,0,0))
=> []
Enyone知道如何找到这个?
Rails将所有内容存储在UTC中,这意味着在分配datetime时使用的任何时区,都将转换为UTC。当活动记录加载新记录时,该日期将显示在当前时区(Time.zone)中,这就是为什么执行 CarRoute.find_by_id(22783).route_time
得到一个CEST日期,但如果你去你的数据库,你会看到一个UTC的日期。
以下内容应该让你清楚:
> Time.zone
=> #< ActiveSupport :: TimeZone:0x007ff6bd390100 @ name =UTC,@ utc_offset = nil,@tzinfo =#< TZInfo :: DataTimezone:Etc / UTC>>
> a = Account.first
=> #<帐户ID:6 .....
> a.updated_at
=> Wed,06 Jul 2016 18:47:32 UTC +00:00
> Time.zone =EST
=> EST
> a.reload
...
> a.updated_at
=>星期三,06七月2016 13:47:32 EST -05:00
当您使用 DateTime.new
日期在utc中创建:
> d = DateTime.new(2016,7,7)
=>星期四,07七月07 00 00:00:00 +0000
> d.utc?
=>真
> a.updated_at.utc?
=> false
在你的哪里查询,你从7 UTC开始,这是上午9点CEST。尝试一下:
DateTime.new(2016,7,7,7,0,0,0).change(offset :'CEST')
I have problem with zones in rails.
I have CarRoute id: 22783, route_time: "2016-07-07 05:30:00"
but in CarRoute.find_by_id(22783).route_time is Thu, 07 Jul 2016 07:30:00 CEST +02:00
So rails add 2h but when I want find by time this route is not works,
CarRoute.where(:id=>22783,:route_time=> DateTime.new(Date.today.year, Date.today.month, Date.today.day, 7, 0, 0, 0)..DateTime.new(Date.today.year, Date.today.month, Date.today.day, 19, 0, 0, 0))
=> []
Enyone know how find this ?
Rails stores everything in UTC, which means that whatever time zone you use when assigning a datetime, its converted to UTC. When active record loads a new record, that date is presented in the current time zone (Time.zone), that's why when you perform CarRoute.find_by_id(22783).route_time
you get a CEST date, but if you go to your database you will see a UTC date.
The following should make it clear for you:
> Time.zone
=> #<ActiveSupport::TimeZone:0x007ff6bd390100 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::DataTimezone: Etc/UTC>>
> a = Account.first
=> #<Account id: 6 .....
> a.updated_at
=> Wed, 06 Jul 2016 18:47:32 UTC +00:00
> Time.zone = "EST"
=> "EST"
> a.reload
...
> a.updated_at
=> Wed, 06 Jul 2016 13:47:32 EST -05:00
When you use DateTime.new
the date is created in utc:
> d = DateTime.new(2016,7,7)
=> Thu, 07 Jul 2016 00:00:00 +0000
> d.utc?
=> true
> a.updated_at.utc?
=> false
In your where query, you're starting at 7 UTC, which is 9 am CEST. Try something like:
DateTime.new(2016,7,7,7,0,0,0).change(offset: 'CEST')
这篇关于在时区找到的Rails - 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!