Read more

Rails: Parsing a time in a desired timezone

Emanuel
February 24, 2021Software engineer at makandra GmbH

Sometimes you want to have a time in a given timezone independent from you Rails timezone settings / system timezone. I usually have this use case in tests.

Example

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Time.parse('2020-08-09 00:00') will return different results e.g. 2020-08-09 00:00:00 +0200 depending on the Rails timezone settings / system timezone. But in this example we always want to have the given time in UTC because that's what the API returns.

it 'returns a valid API response', vcr: true do
  expect(client.get('/users/1')).to have_attributes(
    name: 'Some name',
    role: 'admin',
    created_at: Time.parse('2020-08-09 00:00 UTC')
  )
end

Here are two options by example on how to achieve this in Rails.

Option 1

Time.use_zone('UTC') { Time.zone.parse('2020-08-09 00:00') }
=> Sun, 09 Aug 2020 00:00:00 UTC +00:00

Time.use_zone('Kabul') { Time.zone.parse('2020-08-09 00:00') }
=> Sun, 09 Aug 2020 00:00:00 +0430 +04:30

Option 2

Time.parse('2020-08-09 00:00 UTC')
=> 2020-08-09 00:00:00 UTC

Time.parse('2020-08-09 00:00 +04:30')
=> 2020-08-09 00:00:00 +0430

Option 3

'2020-08-09 00:00'.in_time_zone('UTC')
=> Sun, 09 Aug 2020 00:00:00 UTC +00:00

'2020-08-09 00:00'.in_time_zone('Kabul')
=> Sun, 09 Aug 2020 00:00:00 +0430 +04:30

More details: Why you can't use timezone codes like "PST" or "BST" for Time objects

Posted by Emanuel to makandra dev (2021-02-24 10:03)