class User < ApplicationRecord
validates :timezone, presence: true, inclusion: { in: ActiveSupport::TimeZone.all.map(&:name) }
def local_time
Time.current.in_time_zone(timezone)
end
end
class ApplicationController < ActionController::Base
before_action :set_user_timezone, if: :current_user
private
def set_user_timezone
timezone = cookies[:timezone] || "UTC"
current_user.update(timezone: timezone) if current_user.timezone != timezone
end
end
class AddTimezoneToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :timezone, :string, null: false, default: "UTC"
end
end
<script>
document.addEventListener("DOMContentLoaded", function() {
var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = "timezone=" + timezone + "; path=/";
});
</script>
This snippet automatically detects and stores a user's timezone by capturing it in JavaScript and saving it in a cookie
. On every request, Rails reads this value and updates the user’s timezone in the database if needed. The local_time
method then allows easy conversion to user's local time. This is useful for scheduling, notifications, or showing timestamps in the user's time zone.
Martin Sojka, Maker of CodeSnips