named_timezones.rb

lib/sequel/extensions/named_timezones.rb
Last Update: 2023-12-06 16:41:40 -0800

Allows the use of named timezones via TZInfo (requires tzinfo). Forces the use of DateTime as Sequel’s datetime_class, since historically, Ruby’s Time class doesn’t support timezones other than local and UTC. To continue using Ruby’s Time class when using the named_timezones extension:

# Load the extension
Sequel.extension :named_timezones

# Set Sequel.datetime_class back to Time
Sequel.datetime_class = Time

This allows you to either pass strings or TZInfo::Timezone instance to Sequel.database_timezone=, application_timezone=, and typecast_timezone=. If a string is passed, it is converted to a TZInfo::Timezone using TZInfo::Timezone.get.

Let’s say you have the database server in New York and the application server in Los Angeles. For historical reasons, data is stored in local New York time, but the application server only services clients in Los Angeles, so you want to use New York time in the database and Los Angeles time in the application. This is easily done via:

Sequel.database_timezone = 'America/New_York'
Sequel.application_timezone = 'America/Los_Angeles'

Then, before data is stored in the database, it is converted to New York time. When data is retrieved from the database, it is converted to Los Angeles time.

If you are using database specific timezones, you may want to load this extension into the database in order to support similar API:

DB.extension :named_timezones
DB.timezone = 'America/New_York'

Note that typecasting from the database timezone to the application timezone when fetching rows is dependent on the database adapter, and only works on adapters where Sequel itself does the conversion. It should work with the mysql, postgres, sqlite, ibmdb, and jdbc adapters.

Related module: Sequel::NamedTimezones

Required files

  1. tzinfo