It’s a little known fact, but even though I head up this awesome team of Rails Developers, I get to still get my hands dirty in the code base of applications. We use the excellent FullCalendar JQuery plugin in some of our and our clients applications, but there was a situation where Rails seemed to be ignoring the time zone setting that FullCalendar was sending as part of it’s update method.
FullCalendar would send a string "2013-01-25 11:00:00 +1100"
and Rails would save it to the database as "2013-01-25 11:00:00"
which basically meant it was being saved with it’s time zone information stripped.
This didn’t make sense as the Rails app had the following in application_controller.rb
:
around_filter :set_time_zone
def set_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
And in the config/application.rb
file:
config.time_zone = 'UTC'
config.active_record.default_timezone = 'UTC'
The solution though turned out to be simple, change FullCalendar to post in an ISO string representing the time, instead of a normal Javascript string.
So, we have the following (edited) config for FullCalendar:
$('div#fullcalendar').fullCalendar({
eventSources: [{
url: '/my/calendar_events',
ignoreTimezone: false
}],
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
updateEvent(event);
}
});
Then the update action is:
function updateEvent(the_event) {
$.ajax({
type: 'PUT',
url: "/my/calendar_events/" + the_event.id,
data: { calendar_event: { name: the_event.title,
starts_at: the_event.start.toISOString(),
ends_at: the_event.end.toISOString(),
all_day: the_event.allDay
}
},
dataType: "json"
});
};
Notice the call to toISOString()
in there? That formats the time as "2013-01-25T01:00:00.000Z"
which means it’s always sending UTC time. Rails parses this correctly and saves it into the database correctly and voila, no more time zone issues with FullCalendar.