Rails: Parsing a time in a desired timezone

Posted . Visible to the public.

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

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

Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2021-02-24 09:03)