ruby can calculate the difference between two dates. This includes year, months and days.

The problem can be quite hard, as you have to keep in mind years, months and days. Some years have leap years, not all months are 30 days and so on.

It will calculate the difference in years, months, days and also total number of days difference.

Date difference in ruby

Example

The ruby program below calculates the difference between two dates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/ruby

# In your terminal
# gem install 'time_difference'

require 'date'
require 'time_difference'

# total number of days difference
@current_day = DateTime.now
@created_day = Date.new(1980, 4, 10)

puts @current_day
puts @created_day


diff = TimeDifference.between(@created_day, @current_day).humanize
print "difference "
puts diff

days_between = (@current_day - @created_day.to_date).to_i

print "difference "
puts days_between

This will output something like

1
2
3
4
1980-03-24T00:00:00-05:00
2018-06-16T14:31:32-04:00
difference 38 years, 2 months, 23 days.
difference 13963 days.

Exercises

  1. Calculate the difference between new year and now.
  2. How many days until next year?