How to add N weeks to a given date in Ruby

1 Answer

0 votes
require 'date'

# Adds a specified number of weeks to a given Date object.
# 
# @param base_date [Date] The original Date instance.
# @param weeks [Integer] The number of weeks to add (can also be negative to subtract).
# @return [Date] A new Date instance with the added weeks.
def add_weeks_to_date(base_date, weeks)
  unless base_date.is_a?(Date)
    raise ArgumentError, "base_date must be an instance of Date"
  end

  # Standard Ruby Date objects support integer addition (representing days).
  # We multiply weeks by 7 to convert them into days.
  base_date + (weeks * 7)
end

if __FILE__ == $PROGRAM_NAME
  # Initialize a sample date: November 8, 2026
  target_date = Date.new(2026, 11, 8)
  weeks_to_add = 4

  # Perform the addition
  result_date = add_weeks_to_date(target_date, weeks_to_add)

  # Display the formatted results (Date defaults to ISO-8601 YYYY-MM-DD on string conversion)
  puts "Original date:        #{target_date}"
  puts "After adding #{weeks_to_add} weeks: #{result_date}"
end


# run:
#
# Original date:        2026-11-08
# After adding 4 weeks: 2026-12-06
#

 



answered 14 hours ago by avibootz
...