Search code examples
ruby-on-railsrubytimezone

Determine whether the current Pacific time zone is PST or PDT


We have some Ruby (in a Rails context) that parses expressed time integers into a datetime, and we need to ensure the datetime is parsed into Pacific time:

DateTime.new(2012, 11, 17, 3, 2, 0, 'PST')

However we need to change this to PDT ~half the year. How can we tell at runtime whether we should pass PST or PDT?


Solution

  • You should not attempt to figure out whether to pass PST or PDT (or their equivalent offsets) yourself. Instead, use a time zone identifier, such as those from the IANA tz database (ex: America/Los_Angeles for US Pacific Time), and allow the underlying data for that zone to determine the appropriate offset for the given date and time.

    In Ruby, there are a few different ways to accomplish this.

    • You can use the TZInfo library:

      require 'tzinfo'
      
      tz = TZInfo::Timezone.get('America/Los_Angeles')
      dt = tz.local_datetime(2012, 11, 17, 3, 2, 0)
      

      I believe this library is already included with Rails.

    • You can use the timezone library (though I'm not sure how it differs from tzinfo precisely)

      require 'timezone'
      
      tz = Timezone['America/Los_Angeles']
      dt = tz.time_with_offset(Time.new(2012, 11, 17, 3, 2, 0))
      
    • In Rails specifically, you can use the ActiveSupport::TimeZone class, though I don't recommend it.

      tz = ActiveSupport::TimeZone['Pacific Time (US & Canada)']
      dt = tz.local(2012, 11, 17, 3, 2, 0)
      

      The reasons for not recommending this approach are described in the timezone tag wiki, in the section at the very bottom titled "Rails TIme Zone Identifiers". Alas, if you have an application that needs them - they do still exist in Rails.