shell - Date difference based on yyymm in unix -


#####date1=201609 #### date2=201508 

how calculate difference between these 2 date , output count of no of month ie

201609-201508=13month 

the calculation of time difference complicated task, single calendar type (and there many). many programming languages have built-in support date , time manipulation operations, including calculation of time difference. useful feature available in popular shells date command lacks feature, unfortunately.

therefore, should whether write script in language, or make assumptions such number of days in year.

for example, in perl task done 4 lines of code:

perl -e $(cat <<'perlscript' use time::piece; $t1 = time::piece->strptime($argv[0], '%y%m'); $t2 = time::piece->strptime($argv[1], '%y%m'); printf "%d months\n", ($t1 - $t2)->months; perlscript ) 201609 201508 

however, difference of time::piece objects instance of time::seconds assumes that

there 24 hours in day, 7 days in week, 365.24225 days in year , 12 months in year.

which indirectly confirms words regarding complexity of task.

then let's make same assumption, , write simple shell script:

date1=201609 date2=201508  printf '(%d - %d) / 2629744.2\n' \   $(date -d ${date1}01 +%s) \   $(date -d ${date2}01 +%s) | bc 

where 2629744.2 number of seconds in month, i.e. 3600 * 24 * (365.24225 / 12).

note, of shells not support floating point arithmetic. that's why need invoke external tools such bc.

the script outputs 13. portable version. may run in standard shell, bash, korn shell, or zsh, instance. if want put result variable, wrap printf command in $( ... ):

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 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -