date_arithmetic.rb

lib/sequel/extensions/date_arithmetic.rb
Last Update: 2017-08-01 08:12:00 -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:

add = Sequel.date_add(:date_column, years: 1, months: 2, days: 3)
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)

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

DB[:table].select(add.as(:d)).where(sub > Sequel::CURRENT_TIMESTAMP)

Related module: Sequel::SQL::DateAdd