Library contents

Ruby Date.iso8601

Date.iso8601 parses an ISO date into a Date. Adding one to the result advances the calendar by one day.

A simple example

Date.iso8601

  1. Start with 2024-01-31
  2. Do this Add one calendar day
  3. Result 2024-02-01
January ends on day 31. The next day starts a new month.

Syntax

Ruby syntax
day = Date.iso8601(text) + 1
Run this example in Ruby

Save the program as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Validate and advance a calendar deadline

A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.

First output line2024-03-01
lesson.rb
require 'date'

['2024-02-29', '2023-02-29'].each do |text|
  begin
    puts Date.iso8601(text) + 1
  rescue ArgumentError
    puts 'invalid date'
  end
end
Output
2024-03-01
invalid date

Date checks whether the supplied day exists. Catching ArgumentError also covers the more specific Date::Error used by newer Ruby date libraries.

Ruby documentation for Date.iso8601

Advertisements

Return a borrowed microscope

A school lends a microscope two days before the end of February in a leap year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given28 February 2024 + 2 days
Worked result2024-03-01

Send a year-end reminder

A gallery schedules its reminder one day after the final day of the year. Parse the stated local calendar date and add the indicated number of days. Which date goes on the reminder?

Given31 December 2026 + 1 day
Worked result2027-01-01