Home > front end >  Age calculation program with completed months and days
Age calculation program with completed months and days

Time:09-17

Good afternoon I have a program in bash to calculate the age by entering the data of the year, month and day of birth. But I would also like to calculate the completed months and days. What would be the conditions that I should add to my code. Please help

echo "Enter your year of birth"
read a_nac

echo "Enter your month of birth"
read m_nac

echo "Enter your day of birth"
read d_nac

echo "-----------Birth Date---------"
echo $d_nac $m_nac $a_nac

a_act=$(date  %Y)
m_act=$(date  %m)
d_act=$(date  %d)

echo "-----------Current Date-------------"
echo $d_act $m_act $a_act

let edad=$a_act-$a_nac

if [ $m_act -lt $m_nac ]; then

    ((edad--))

    elif [ $m_nac -eq $m_act -a $d_act -lt $d_nac ]; then
       
        ((edad--))
    fi

echo "-----------Age-------------------"
echo "You have" $edad "years"

CodePudding user response:

It's a bit complex to find a generic solution. For the dates after the epoch we can convert both the dates with date %s and make a plain subtraction.

A more generic solution follows:

echo "Enter your year of birth"
read a_nac

echo "Enter your month of birth"
read m_nac

echo "Enter your day of birth"
read d_nac

echo "-----------Birth Date---------"
echo $d_nac $m_nac $a_nac

a_act=$(date  %Y)
m_act=$(date  %-m)
d_act=$(date  %-d)

echo "-----------Current Date-------------"
echo $d_act $m_act $a_act

let years=$a_act-$a_nac

if [ $m_act -lt $m_nac ]; then
    ((years--))
    let months=$m_nac-$m_act
elif [ $m_act -ge $m_nac ]; then
    let months=$m_act-$m_nac
elif [ $m_nac -eq $m_act -a $d_act -lt $d_nac ]; then
    ((years--))
fi
if [ $d_act -lt $d_nac ]; then
    ((months--))
    let days=30-$d_nac $d_act
else
    let days=$d_act-$d_nac
fi

echo "-----------Age-------------------"
echo "You have $years years, $months months, $days days"

The line

let days=30-$d_nac $d_act

does not take into account that not all the months have 30 days and the case of leap months. The correction is left to the reader ;)

  • Related