年龄计算程序,包含完整的月和日



下午好,我在bash中有一个程序,通过输入出生年、月、日的数据来计算年龄。但我也想计算完成的月份和天数。我应该在代码中添加什么条件呢?请帮助

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"

找到一个通用的解决方案有点复杂。对于epoch之后的日期,我们可以用date +%s转换两个日期并进行简单的减法。

一个更通用的解决方案如下:

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"

let days=30-$d_nac+$d_act

没有考虑并非所有月份都有30天以及闰月的情况。更正留给读者;)

最新更新