Working with Chronic and Time-zones
Chronic is an amazing gem. It allows you to do things like take "tomorrow at 10" and get an actual date and time from it. It's easy to use
>> require 'chronic'=> []
>> Chronic.parse("tomorrow at 10")
=> Thu Nov 12 10:00:00 -0800 2009This essentially allows you to process free-form text into Time objects. However, there is one big gotcha if you're using time-zones that I recently had some trouble with.
Chronic calculates the time in the local time-zone - thats the machines time-zone, not the time-zone set as the default in the environment.rb file usingconfig.time_zone = 'UTC'nor the time-zone that you explicitly set using Time.zone = 'Tokyo'Let's say your machine (your development laptop let's say) is on Pacific US time. If we do this>> Time.zone = 'Tokyo'
>> Chronic.parse("tomorrow at 10am") we get Thu Nov 12 10:00:00 -0800 2009 (assuming tomorrow is November 12th 2009). This is the time formatted for the local time-zone, Pacific US time, not the one for Tokyo as you might expect - whoops. This can be especially confusing/fustrating if your development machines and production machines doens't share the same local time. Everything could look correct during development because the local time and your default time-zone are the same, let's say Pacific US - great everything looks good, your times are coming out correct. But when you move to production your local time in production is UTC and now your times are off by 8 hours and you don't know why. OK, now that we know it's a problem, how do we fix it?>> Time.zone = 'Tokyo'
>> my_time = Chronic.parse("tomorrow at 10am")
>> real_time = Time.zone.parse(my_time.strftime("%Y-%m-%d %H:%M:%S")) which will give us Thu, 12 Nov 2009 10:00:00 JST +09:00 which is the time correctly formatted for Tokyo, 9 hours ahead of UTC time. So unfortunately we need to do an extra conversion step, but it's a small price to pay to get the power of Chronic.
EDIT: Thanks to Cuth for pointing this out. This is not in the Chronic RDoc here, but is mentioned in the Git readme here.
You can also set the time zone explicitly like this
>> Chronic.time_class = Time.zone
So now, if we use the example above, where the time zone is Tokyo, Chronic.parse("tomorrow at 10am") should now correctly return Thu, 12 Nov 2009 10:00:00 JST +09:00

