Calculate difference in months between two dates in Unix?
How about:
#!/bin/bashDATE1=201712DATE2=201801y1=${DATE1:0:4}m1=${DATE1:4:2}y2=${DATE2:0:4}m2=${DATE2:4:2}diff=$(( ($y2 - $y1) * 12 + (10#$m2 - 10#$m1) ))echo $diff
I have prepared the following bash function for you let me know if it is clear:
#!/usr/bin/env bashDATE1=201712DATE2=201801function dateDiffMonth() { local y1=$(date -d "$1""01" '+%Y') # extract the year from your date1 local y2=$(date -d "$2""01" '+%Y') # extract the year from your date2 local m1=$(date -d "$1""01" '+%m') # extract the month from your date1 local m2=$(date -d "$2""01" '+%m') # extract the month from your date2 echo $(( ($y2 - $y1) * 12 + (10#$m2 - 10#$m1) )) #compute the months difference 12*year diff+ months diff -> 10# force the shell to interpret the following number in base-10}RESULT=`dateDiffMonth $DATE1 $DATE2`echo "there is a gap of $RESULT months betwen $DATE2 and $DATE1"