Codectionary / Developer documentation / Ruby

Date Arithmetic

Date represents immutable calendar dates. Adding an integer advances by days and subtracting two dates produces an exact rational day difference. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

Date.iso8601(text); date + days; finish - start

Examples

Date Arithmetic

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

require "date"
start = Date.iso8601("2024-02-28")
finish = start + 2
puts start + 1
puts finish
puts (finish - start).to_i
  1. Expected output: 2024-02-29 2024-03-01 2
  2. Date arithmetic crosses leap day correctly. The original start remains unchanged.

Best practices

  • Use explicit formats such as iso8601 for machine input.
  • Use Time for instants with a clock time and offset.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading