Paluy on Miscellaneous

Of course I'm an optimist - I don't see much point in being anything else. - Winston Churchill

Caution - To_time in Rails

TL;DR

Attention on time zone while using today.to_time in your Rails application!

Ruby to_time in your Rails application

Suppose, you need to convert some date to datetime. You can use the Ruby to_time method:

1
2
3
4
5
6
7
date = Date.new(2013, 04, 15)

date.to_time            # 2013-04-15 00:00:00 +0300
date.to_time(:local)    # 2013-04-15 00:00:00 +0300
# The Time Zone depends on your local machine

date.to_time(:utc)      # 2013-04-15 00:00:00 +0000

If your server time zone is UTC, but Rails application has different time zone, for example:

1
config.time_zone = 'Central Time (US & Canada)'

converting from date to time will ignore Rails settings!

It happens, when you need to output your date in epoch format (for example: in json).

I suggest to convert your date to utc and than to epoch.

1
epoch = date.to_time(:utc).to_i

Then, apply local time zone using JavaScript::

1
var date = new Date(epoch);

Comments