This question was here for other languages, so let here be one for Ruby.
How do I calculate number of complete years that have passed from a given date? As you prob
I think this will always work, even for someone with a birthday near a leap day:
require 'date'
def calculate_age(start_date, end_date)
end_date.year - start_date.year - ((end_date.month > start_date.month || (end_date.month == start_date.month && end_date.day >= start_date.day)) ? 0 : 1)
end
puts calculate_age( Date.strptime('03/02/1968', '%m/%d/%Y'), Date.strptime('03/02/2010', '%m/%d/%Y'))
The calculated age with this method in the example call above is 42, which is correct despite 1968 being a leap year and the birthday being near a leap day.
Plus, this way there is no need to create a local variable.