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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)