date_arithmetic.rb

Path: lib/sequel/extensions/date_arithmetic.rb
Last Update: Sun Oct 02 21:06:53 +0000 2016

frozen-string-literal: true

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

[Validate]