User Agents

Web browsers and everyday web tech, explained

Display Rails Datetime in Browser Timezone Guide

· 6 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To display a datetime in the timezone of a browser using Ruby on Rails, you must shift the responsibility of time formatting from the server to the client. Because Rails runs on a server (which typically uses UTC), it has no inherent knowledge of the end-user's local clock or geographic location. The most reliable method is to render the timestamp in a standardized ISO 8601 format and use a JavaScript library or the native browser Intl API to convert that UTC string into the user's local time upon page load.

What You'll Need

  • A Ruby on Rails application (version 6.0 or newer recommended).
  • Basic familiarity with ERB or Slim templates.
  • Access to the application's JavaScript bundle (via Importmaps, Esbuild, or Webpacker).
  • A database column of type datetime or timestamp.

Step-by-Step

  1. Ensure Server-Side Storage is UTC: Before implementing client-side display, verify that your Rails application is configured to store times in UTC. This is the Rails default, but check config/application.rb for config.time_zone = 'UTC'. Storing data in UTC prevents data corruption and simplifies the math when converting to various global timezones.
  2. Create a Data Attribute for the Timestamp: Instead of rendering the time directly as text (which would show the server's time), wrap the time in an HTML element with a data-datetime attribute. Use the to_fs(:iso8601) or iso8601 method to ensure the string is in a format JavaScript can parse reliably.

    <span class="local-datetime" data-datetime="@post.created_at.iso8601">@post.created_at</span>

    The text inside the span acts as a fallback for users with JavaScript disabled, while the data attribute holds the machine-readable UTC time for the script.
  3. Implement the JavaScript Conversion Logic: Create a JavaScript function that finds all elements with the local-datetime class, reads the UTC string from the data attribute, and converts it using the browser's Intl.DateTimeFormat object. This native API is preferred over heavy libraries like Moment.js because it is lightweight and built into all modern browsers.
  4. Write the Conversion Script: Add the following logic to your application's JavaScript entry point (e.g., app/javascript/application.js):

    document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.local-datetime').forEach(el => { const utcDate = new Date(el.dataset.datetime); const localTime = new Intl.DateTimeFormat(navigator.language, { dateStyle: 'medium', timeStyle: 'short' }).format(utcDate); el.textContent = localTime; }); });

    This script iterates through every marked timestamp, detects the user's browser language and timezone via navigator.language, and updates the inner text of the element.
  5. Handle Dynamic Content (Turbo/Hotwire): If your Rails app uses Turbo (formerly Turbolinks), the DOMContentLoaded event only fires on the first page load. To ensure dates are converted after a Turbo navigation, wrap your logic in a turbo:load event listener:

    document.addEventListener('turbo:load', () => { // Conversion logic here });
  6. Test Across Timezones: Open your browser's Developer Tools, go to the "Sensors" tab (in Chrome), and override your geolocation or timezone. Refresh the page to confirm that the displayed time shifts correctly based on the simulated location.

Common Mistakes

One of the most frequent errors is attempting to handle the timezone conversion in the Rails controller or helper. While you can use the Time.use_zone block in Rails, this requires the user to manually select their timezone in a profile setting and save it to the database. If you want the browser's current setting without requiring a user account or a settings page, server-side conversion is impossible because the server does not receive the timezone header in standard HTTP requests.

Another common mistake is using Date.now() or local JavaScript date objects without specifying the UTC offset. If you pass a date string to JavaScript that doesn't end in 'Z' (the UTC indicator) or include an offset, the browser may assume the date is already in local time, leading to a "double offset" where the time is shifted twice.

Finally, developers often forget about accessibility. If the JavaScript fails to load or the user has it disabled, the page should still be readable. Always provide a human-readable fallback inside the HTML tag so that the page doesn't appear empty or broken during the loading phase.

Tips

For applications with a high volume of timestamps (such as a dense activity feed), calling Intl.DateTimeFormat inside a loop can be slightly inefficient. Instead, instantiate the formatter once outside the loop and reuse it for every element. This reduces memory overhead and improves rendering speed on lower-end mobile devices.

If you need highly specific formatting (e.g., "2 hours ago"), consider using a library like date-fns or dayjs. While the native Intl API is great for absolute dates, relative time formatting is more complex to implement from scratch. These libraries provide a formatDistanceToNow function that works seamlessly with the UTC dates provided by Rails.

To enhance the user experience, you can add a CSS transition or a subtle fade-in effect to the timestamps. This prevents the "flash of unformatted content" (FOUC) where the user briefly sees the UTC time before the JavaScript snaps it to the local timezone.

Troubleshooting

The time is off by exactly X hours: This usually indicates a mismatch in how the date string is being parsed. Check your HTML source. If the string looks like 2026-12-02 10:00:00 without a Z or +00:00 at the end, JavaScript will treat it as local time. Ensure you are using .iso8601 in Rails to produce 2026-12-02T10:00:00Z.

The dates don't update when navigating between pages: This is almost certainly a Turbo/Turbolinks issue. Because Turbo replaces the body of the page without a full reload, the standard window.onload or DOMContentLoaded events do not fire. Change your event listener to turbo:load or turbolinks:load depending on your version of Rails.

The date format looks strange on different browsers: The navigator.language property tells the browser to use the user's system locale. If you want a consistent format across all users regardless of their location (e.g., always MM/DD/YYYY), replace navigator.language with a specific locale string like 'en-US' in the Intl.DateTimeFormat constructor.

Frequently Asked Questions

Can I do this without JavaScript?

No. The server cannot detect the browser's local timezone automatically. To do this without JavaScript, you must ask the user to select their timezone from a dropdown menu, save that preference to their user profile in the database, and then use Time.use_zone(current_user.time_zone) in your Rails controllers.

Is ISO 8601 the best format for this?

Yes. ISO 8601 is the international standard for representing dates and times. It is natively supported by the JavaScript Date constructor and eliminates ambiguity regarding day/month order and timezone offsets.

Will this work for users in the same timezone as the server?

Yes. If the user and server are both in UTC, the JavaScript conversion will simply result in the same time. The logic remains consistent regardless of the geographic distance between the client and the server.

Does this affect the data stored in the database?

No. This method only changes how the data is presented to the user. The underlying data in your PostgreSQL or MySQL database remains in UTC, ensuring your data integrity is preserved for reporting and calculations.

What happens if the user's browser is very old?

The Intl API is supported in all modern browsers. For extremely old browsers (like IE11), you would need a polyfill or a library like Moment.js. However, for 99% of modern web traffic, the native API is sufficient and significantly faster.