How to check if a date is in the future with Ruby

2 Answers

0 votes
require 'date'

# Checks if a given year, month, and day are strictly in the future compared to today.
# Returns true if the date is in the future, false otherwise.
def date_in_future?(year, month, day)
  # 1. Construct the target date (raises ArgumentError if invalid, e.g., Feb 30)
  target_date = Date.new(year, month, day)

  # 2. Get today's date (Date.today strips out time components automatically)
  today = Date.today

  # 3. Compare dates directly using standard comparison operators
  target_date > today
rescue ArgumentError => e
  # Handle invalid calendar dates gracefully
  STDERR.puts "Error: Invalid calendar date provided (#{e.message})"
  false
end

# --- Complete Runnable Program Example ---
if __FILE__ == $0
  test_year = 2035
  test_month = 6
  test_day = 15

  puts "Checking date: #{test_year}-#{test_month}-#{test_day}"

  if date_in_future?(test_year, test_month, test_day)
    puts "Result: The date is in the FUTURE."
  else
    puts "Result: The date is NOT in the future."
  end
end


# run:
#
# Checking date: 2035-6-15
# Result: The date is in the FUTURE.
#

 



answered 1 hour ago by avibootz
0 votes
require 'time'

# Checks if a date is in the future using Time objects normalized to midnight.
def time_in_future?(year, month, day)
  # 1. Create target time at midnight local time
  target_time = Time.new(year, month, day, 0, 0, 0)

  # 2. Get current time and normalize it to midnight (00:00:00)
  now = Time.now
  today_midnight = Time.new(now.year, now.month, now.day, 0, 0, 0)

  # 3. Compare timestamps
  target_time > today_midnight
rescue ArgumentError => e
  STDERR.puts "Error: Invalid date values (#{e.message})"
  false
end

# --- Complete Runnable Program Example ---
if __FILE__ == $0
  test_year = 2035
  test_month = 6
  test_day = 15

  puts "Checking date: #{test_year}-#{test_month}-#{test_day}"

  if time_in_future?(test_year, test_month, test_day)
    puts "Result: The date is in the FUTURE."
  else
    puts "Result: The date is NOT in the future."
  end
end


# run:
#
# Checking date: 2035-6-15
# Result: The date is in the FUTURE.
#

 



answered 1 hour ago by avibootz
...