Last active
October 13, 2025 16:18
-
-
Save harsh183/2ceb3951ba33bc57ee4fcf2f90f643e2 to your computer and use it in GitHub Desktop.
using ruby nice datetime things to calculate time in a place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Load Ruby's standard Date library | |
| require 'date' | |
| # Travel data as key-value map where arrival date points to departure date | |
| # Each pair represents how long spent in the country during that visit | |
| # Note: Most recent arrival (2025-03-30) uses projected departure of Nov 1, 2025 | |
| trips_data = { | |
| '2025-03-30' => '2025-11-01', # Current visit - projected departure Nov 1, 2025 | |
| '2025-03-14' => '2025-03-15', # Short 1-day visit | |
| '2025-02-09' => '2025-03-11', # 30-day visit | |
| '2025-01-18' => '2025-02-08', # 21-day visit | |
| '2024-08-20' => '2024-12-13' # 115-day visit | |
| } | |
| puts "=" * 60 | |
| puts "TRAVEL DURATION CALCULATOR" | |
| puts "Using Ruby's standard Date library" | |
| puts "=" * 60 | |
| puts | |
| # Parse dates using Ruby's standard Date parsing and calculate durations | |
| trips = [] | |
| trips_data.each do |arrival_date_str, departure_date_str| | |
| arrival_date = Date.parse(arrival_date_str) | |
| departure_date = Date.parse(departure_date_str) | |
| # Calculate duration using Ruby's standard date arithmetic | |
| # We add one since officials will often use both fenceposts as includesive | |
| duration_days = (departure_date - arrival_date).to_i + 1 | |
| trips << { arrival_date:, departure_date:, duration_days: } | |
| end | |
| # Sort trips by arrival date for chronological display | |
| trips.sort_by! { |trip| trip[:arrival_date] }.reverse! | |
| puts "TRIP DURATIONS:" | |
| puts "-" * 60 | |
| trips.each_with_index do |trip, index| | |
| arrival_date = trip[:arrival_date] | |
| departure_date = trip[:departure_date] | |
| duration = trip[:duration_days] | |
| puts "Trip #{index + 1}:" | |
| puts " Arrival: #{arrival_date.strftime('%Y-%m-%d')}" | |
| puts " Departure: #{departure_date.strftime('%Y-%m-%d')}" | |
| puts " Duration: #{duration} days" | |
| puts | |
| end | |
| puts "=" * 60 | |
| # Display which Ruby methods were used | |
| puts "Ruby standard library methods used in this calculation:" | |
| puts "- require 'date' - Ruby's standard Date library" | |
| puts "- Date.parse() - for parsing date strings" | |
| puts "- Date arithmetic (date1 - date2) - for calculating differences" | |
| puts "- .strftime() - for formatting date output" | |
| puts "- .to_i - for converting date differences to integer days" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment