开发者

timezone and yesterday

开发者 https://www.devze.com 2023-03-22 10:41 出处:网络
I have a problem with rails timezones. application.rb 开发者_开发知识库config.time_zone = \'Athens\'

I have a problem with rails timezones.

application.rb

开发者_开发知识库config.time_zone = 'Athens'

controller

@from = (Time.zone.now-1.day).to_date
@to = (Time.zone.now).to_date
Entry.where(:created_at => @from..@to)

This query supposed to list entries which were created yesterday. When i list entries, i see that some entries were created today.

For example:

It is 5:53 am now and i see that the last entry which was created yesterday was created 3 hours ago, it mustn't be smaller than 6 hours. Any help will be appreciated.


Your database is probably using UTC timestamps (at least it should be) but Time.zone.now is in your local timezone. Then you call to_date and lose the timezone information. Try this:

@from = (Time.zone.now - 1.day).beginning_of_day.utc
@to   = (Time.zone.now).beginning_of_day.utc
Entry.where(:created_at => @from..@to)

So you call beginning_of_day to get back to 00:00:00 and then convert to UTC with utc to get your timestamps into UTC to match the database. You want to keep the time-of-day around all through this so that you don't lose track of what's going during the timezone transitions.

0

精彩评论

暂无评论...
验证码 换一张
取 消