When running the following query in psql I get back 7 results:
SELECT generate_series('2012-10-14', CURRENT_DATE, interval '1 day'); # 7
However when I run the exact same query in my rails application, I get 8 results:
result = ActiveRecord::Base.connection.execute "SELECT generate_series('2012-10-14', CURRENT_DATE, interval '1 day');"
puts result.count # 8
It seems like this has something to do w/ timezones but I don’t know what the problem could be. I have the following in my application.rb
config.time_zone = 'Eastern Time (US & Canada)'
This is the same time zone setting that I have in my postgresql.conf
I’m confused at to why my rails application is adding an additional day to my results. Can anyone provide some insight?
This only seems to happen towards the end of the day (after 8PM) so this is what makes me think it’s something w/ time zone offsets.
The version of
generate_seriesthat you’re using is working with timestamps, not dates. So your'2012-10-14'andcurrent_dateare getting converted totimestamp with time zones andgenerate_seriesis producing a set oftimestamp with time zones; compare these:The first one has time zones, the second one doesn’t.
But, the
current_datealways gets converted to a timestamp with the database session’s time zone adjustment applied. The Rails session will talk to the database in UTC, yourpsqlsession is probably using ET.If you manually specify the current date and explicitly work with
timestamps:then you’ll get the same seven results in both because there’s no time zone in sight to make a mess of things.
The easiest way to ignore time zones is to use the integer version of
generate_seriesand the fact that adding an integer to a date treats the integer as a number of days:That will give you the same seven days without time zone interference. You can still use the
current_date(which has no time zone since SQL dates don’t have time zones) by noting that the difference between two dates is the number of days between them (an integer):and from Rails:
BTW, I hate time zones, hate and despise them.