Calculating the time difference is usually a challenge even for one type of calendar (and there are many ). Many programming languages have built-in support for date and time processing operations, including the calculation of time differences. But the most useful feature available in popular shells is a team datethat lacks this feature, unfortunately.
Therefore, we must write a script in another language or make some assumptions, such as the number of days in a year.
, Perl :
perl -e $(cat <<'PerlScript'
use Time::Piece;
my $t1 = Time::Piece->strptime($ARGV[0], '%Y%m');
my $t2 = Time::Piece->strptime($ARGV[1], '%Y%m');
printf "%d months\n", ($t1 - $t2)->months;
PerlScript
) 201609 201508
Time::Piece Time::Seconds, ,
24 , 7 , 365.24225 12 .
.
script:
DATE1=201609
DATE2=201508
printf '(%d - %d) / 2629744.2\n' \
$(date -d ${DATE1}01 +%s) \
$(date -d ${DATE2}01 +%s) | bc
2629744.2 - , .. 3600 * 24 * (365.24225 / 12).
. . , bc.
script 13. . , , Bash, Korn Zsh. , printf $( ... ):
months=$(printf '(%d - %d) / 2629744.2\n' \
$(date -d ${DATE1}01 +%s) \
$(date -d ${DATE2}01 +%s) | bc)
printf '%d - %d = %d months\n' $DATE1 $DATE2 $months