I'm working on Rails application that let users to make max 2 posts for each day, very simple.
My problem is how to manage different timezone where different users lives. For example if I live in London and the day start at 00.00
and finish at 23.59
the posts count will reset at 00.00
, but for another users live in New York the counter will then reset at different time. (not at 00.00
) How can I manage this situation?
I hope I explained myself.
UPDATE 1
@Cluster
The problem with your code is that time_zone.utc_offset
give a wrong time delta:
1.9.3p194 :123 > time_zone = ActiveSupport::TimeZone.new("Prague")
=> (GMT+01:00) Prague
1.9.3p194 :124 > DateTime.now.utc.midnight - time_zone.utc_offset
=> Thu, 10 Apr 2003 00:00:00 +0000
Why that?
Instead of that I've found useful this code:
User.posts.where(:created_at => DateTime.now.in_time_zone(time_zone).beginning_of_day..DateTime.now.in_time_zone(time_zone).end_of_day).count
It seems to get the correct number of messages between the user's day (with user's timezone). What do you think?
UPDATE 2
@Cluster
What's the difference between:
User.posts.where(:created_at => DateTime.now.in_time_zone(utc_time_zone).beginning_of_day..DateTime.now.in_time_zone(utc_time_zone).end_of_day).count
and yours:
1.9.3p327 :015 > time_zone = ActiveSupport::TimeZone.new("Prague")
=> (GMT+01:00) Prague
1.9.3p327 :016 > Time.zone.now.utc.midnight - time_zone.utc_offset
=> 2013-02-15 23:00:00 UTC
in terms of performances and way of doing?
UPDATE 3
Actually the code in your example doesn't work, look here:
# WRONG
1.9.3p194 :096 > user.posts.where('created_at > ?', Time.zone.now.utc.midnight - my_time_zone.utc_offset).count
(0.2ms) SELECT COUNT(*) FROM "messages" WHERE "messages"."sender_id" = 5 AND (created_at > '2013-02-15 23:00:00.000000')
=> 4
# CORRECT
1.9.3p194 :098 > users.posts.where(:created_at => DateTime.now.in_time_zone(my_time_zone).beginning_of_day..DateTime.now.in_time_zone(my_time_zone).end_of_day).count
(0.3ms) SELECT COUNT(*) FROM "messages" WHERE "messages"."sender_id" = 5 AND ("messages"."created_at" BETWEEN '2013-02-16 23:00:00.000000' AND '2013-02-17 22:59:59.000000')
=> 0