I find its frustating when you can’t set the right time zone for your application / website. Currently i’m handling project that needs to display today events and upcoming events. I got task to migrate it into new server. But when its migrated the features is still not correct.

MySQL

First, i thought it was wrong time zone for mysql then i changed mysql default time zone. You need to see current mysql time zone using :

1
SELECT @@global.time_zone;

then you can change it in your desired time zone :

1
SET @@global.time_zone='+07:00';

or you can change my.cnf by adding default time zone :

1
default_time_zone='+07:00'

Rails

Changing mysql default time zone seems not solve that problem. I thought it was because Rails not setting the right time zone so i changed

1
application.rb
to my desired time zone :

config.time_zone = 'Jakarta'

restart the application and reload my rails console but still its not solve that problem. I found that

1
Time.now
and
1
Time.zone.now
returns different values because
1
Time.now
return local date but
1
Time.zone.now
return the desired time zone in
1
application.rb
. If you want to make
1
Time.zone.now
returning local date then you can adjust
1
application.rb
:

config.active_record.default_timezone = :local

Local server time

But its still not solved. Why?

Finally, i found that all code in the application was using

1
Time.now
so instead changing all
1
Time.now
into
1
Time.zone.now
i changed local date. You need to display current date of your local using terminal :

1
$ date

You will get something like this (based on your local datetime setting):

1
Wed Sep 10 21:24:56 EDT 2014

Thats it. I changed local date to my desired date :

1
$ sudo dpkg-reconfigure tzdata

just follow the instruction and choose what you want. Don’t forget to restart cron as its still running in your past time zone

1
$ /etc/init.d/cron stop
1
$ /etc/init.d/cron start

Conclusion

If you have configured time zone in your application you should using

1
Time.zone.now
instead
1
Time.now
as
1
Time.now
return your local / system time.

Time.now # => Returns system time and ignores your configured time zone.
Time.zone.now # => Returns your desired time zone.

Hope this will help you!