How to display time to users in their local timezones?

Hi :wave:

I’m working on an event webpage where content creators could enter new events on Netlify CMS. I got the Netlify CMS UI part but a bit confused about how to display dates and times to the visitors.

Let’s say the content creator is located in Germany and creates an event on CMS at 16.00 GMT +1. According to Netlify Documentation Netlfiy CMS stores timestamps as datetime objects in UTC by default. ( if I don’t set locale to any moment.js token such as LLL)

My question is what is the best practice to display this date-time to the visitor in his local time?

  • If I use ruby methods such as time.getlocal in my .erb templates, Middleman will build it based on the local time zone of the build environment, is it true?
  • Is there a method to get the time zone of the visitor from her browser then use it in the template? Is it possible to do it without using javascript or any .js based library such as moment.js?
  • How to fix the time zone of the build environment on config.rb?

Thanks :slight_smile:

I think you’ll have to convert the time object with JavaScript, as your middleman build won’t have any input on where your users are fetching it from. I recommend you take a look at moment JS’ timezone functionality: https://momentjs.com/timezone/docs/

Thank you for your answer. I also thank you for the middleman-netlify-cms repo, I used it for this project.

For now, I skip the moment.js and chose to display event times converting to the German time-zone where most visitors are living at. Below I summarized it for others, any improvements are welcome.

To fix the time-zone on config.rb you need to add:

require "tzinfo"
Time.zone = "Berlin"

To allow content creators to see time in their local zone on CMS UI you need to set picker_utc: false on your collection under /source/admin/config.yml ( it’s false by default, you could skip also)

- {label: Event Time, name: time, picker_utc: false, widget: datetime }

Finally on your templates render time data with .getlocal() method by passing the Time.zone argument into it.

For example

<%= event.time.getlocal(Time.zone) %>

will print:

2021-01-10 13:00:00 +0100

If you want to print it in hh:mm format only you might use .strftime with desired format directives

<%= event.time.getlocal(Time.zone).strftime("%k:%M %:z") %>

will print:

13:00  +01.00