Skip to content

Instantly share code, notes, and snippets.

@robinclart
Created April 17, 2012 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinclart/2404095 to your computer and use it in GitHub Desktop.
Save robinclart/2404095 to your computer and use it in GitHub Desktop.
A module and a class to deal with birthday
require "date"
module Birthday
def birthday(year_of_birthday = Date.today.year)
if birthdate.leap?
year_of_birthday += 1 until Date.new(year_of_birthday).leap?
end
Date.new(year_of_birthday, birthdate.month, birthdate.day)
end
def birthday?(other_date = Date.today)
other_date.month == birthdate.month && other_date.day == birthdate.day
end
def years_from(other_date)
((other_date - birthdate).to_i / 365.2422).floor
end
def years_old
years_from Date.today
end
def next_birthday(other_date = Date.today)
birthday other_date.year + (before_birthday?(other_date) ? 0 : 1)
end
def previous_birthday(other_date = Date.today)
birthday other_date.year + (after_birthday?(other_date) ? 0 : -1)
end
def before_birthday?(other_date = Date.today)
other_date < birthday(other_date.year)
end
def after_birthday?(other_date = Date.today)
other_date > birthday(other_date.year)
end
def centenarian?(other_date = Date.today)
years_from(other_date) >= 100
end
def newborn?(other_date = Date.today)
years_from(other_date) == 0
end
end
# Examples
#
# puts Birthdate.parse("02 nov 1986").next_birthday
# # >> 2012-11-02
class Birthdate < Date
include Birthday
def birthdate
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment