Created
May 10, 2016 10:04
-
-
Save Nereare/57e001373439df2e08afdae0ce0b195f to your computer and use it in GitHub Desktop.
Age calculator, specifically for pediatric pacients, output in portuguese.
This file contains 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
require 'date' | |
DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] | |
# This method takes a date in the string format "DD/MM/YYYY" and returns | |
# a Time object. | |
def birthday_timestamp_time(date) | |
birthday = date.split('/') | |
Time.new(birthday[2], birthday[1], birthday[0]) | |
end | |
# This method takes a birthday in the string format "DD/MM/YYYY" and returns | |
# the person's age. | |
def birthday_timestamp_age(date) | |
borrowed_month = false | |
current_date = Time.new | |
birth_date = birthday_timestamp_time(date) | |
# Get days for this year | |
if current_date.to_date.leap? | |
DAYS_IN_MONTH[2] = 29 | |
end | |
day = current_date.day - birth_date.day | |
month = current_date.month - birth_date.month | |
year = current_date.year - birth_date.year | |
if day < 0 | |
# subtract month, get positive # for day | |
day = DAYS_IN_MONTH[birth_date.month] - birth_date.day + current_date.day | |
month -= 1 | |
borrowed_month = true | |
end | |
if month < 0 | |
# subtract year, get positive # for month | |
month = 12 - birth_date.month + current_date.month | |
if borrowed_month == true | |
month -= 1 | |
end | |
year -= 1 | |
end | |
# Error-handling for future date | |
if year < 0 | |
year, month, day = 0, 0, 0 | |
end | |
"Idade: #{year}a,#{month}m,#{day}d" | |
end | |
puts "Data de Nascimento:" | |
$oe = gets | |
birthday_timestamp_age($oe) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment