Saturday, January 7, 2012

Calculate difference between two dates in bash?


The easiest way is to convert both the dates to unix timestamp (which is the number of seconds from Jan 1, 1970). Once done simply substract them and divide by 86400. 


For e.g., date --date "2012-01-06" +%s Converts the date to number of seconds..



d1=`date --date "2012-01-06" +%s`
d2=`date +%Y-%m-%d`
d2=`date --date "$d2" +%s`


diff=$((d2-d1))
days=`echo $((diff/86400))`

The variables days will contain the difference in days between d1 and d2. Where, d1 is 2012-01-06 (yyyy-mm-dd format) and d2 is current date. 

Enjoy.

1 comment:

  1. Thx for the Article it helped me to realized where i had mistake

    ReplyDelete