Last Update: 2022-10-21 08:19:04 -0700

The date_arithmetic extension adds the ability to perform database-independent addition/substraction of intervals to/from dates and timestamps.

First, you need to load the extension into the database:

DB.extension :date_arithmetic

Then you can use the Sequel.date_add and Sequel.date_sub methods to return Sequel expressions (this example shows the only supported keys for the second argument):

add = Sequel.date_add(:date_column, years: 1, months: 2, weeks: 2, days: 1)
sub = Sequel.date_sub(:date_column, hours: 1, minutes: 2, seconds: 3)

In addition to specifying the interval as a hash, there is also support for specifying the interval as an ActiveSupport::Duration object:

require 'active_support/all'
add = Sequel.date_add(:date_column, 1.years + 2.months + 3.days)
sub = Sequel.date_sub(:date_column, 1.hours + 2.minutes + 3.seconds)

By default, values are casted to the generic timestamp type for the database. You can override the cast type using the :cast option:

add = Sequel.date_add(:date_column, {years: 1, months: 2, days: 3}, cast: :timestamptz)

These expressions can be used in your datasets, or anywhere else that Sequel expressions are allowed:

DB[:table].select( > Sequel::CURRENT_TIMESTAMP)

On most databases, the values you provide for years/months/days/etc. must be numeric values and not arbitrary SQL expressions. However, on PostgreSQL 9.4+, use of arbitrary SQL expressions is supported.

Related module: Sequel::SQL::DateAdd