New Rails handles a lot of timezone stuff for you. Set the appropriate time zone for the request and get an object from the DB, it’s created_at date will be translated from UTC to the request’s time zone.
Rails doesn’t do anything with the Ruby enhancements that create time objects from dates. Like:
Date.today.end_of_day
That’ll be in the server’s time zone. Ick.
I needed to find the beginning of a day as related to the request’s timezone. I moved the fix into some date extensions:
class ::Date
def beginning_of_day_in_zone
Time.zone.parse(self.to_s)
end
alias_method :at_beginning_of_day_in_zone, :beginning_of_day_in_zone
alias_method :midnight_in_zone, :beginning_of_day_in_zone
alias_method :at_midnight_in_zone, :beginning_of_day_in_zone
def end_of_day_in_zone
Time.zone.parse((self+1).to_s) - 1
end
end
So now we have:
Time.zone = "Auckland"
=> "Auckland"
> Date.today.beginning_of_day
=> Tue Dec 09 00:00:00 -0600 2008
> Date.today.beginning_of_day_in_zone
=> Tue, 09 Dec 2008 00:00:00 NZDT +13:00
Realistically, I think Rails could be improved in this area. Or maybe I’m missing out on a better way to take a date object and make it zone-aware for generating related times. I spent more than an hour reading through the Rails date and time extensions and realized I need to keep my timezone pain relegated to the work week. For the time being, the above is a nice crutch for my current needs.