Date Difference

Hello Guys,

I am trying to find the difference between two dates & need to assign that value in a variable for further code. I am able to find the difference but have some issues with it.

  1. Value is coming in decimal point ( 82.95833333333333333333 ) which should be actually 83 days
  2. I am able to print the difference with echo command but when I assign it to some variable it fails.

Can someone please take a look at it & help to sort out ? below is the code I am using now :

Code:

Date1=2020-05-26
Date2=2020-03-04
echo "`date -d $expdate +%s` - `date -d $today +%s`)/(24*3600)" |bc -l

If I try to store a value in a variable called Diff="`date -d $expdate +%s` - `date -d $today +%s`)/(24*3600)" |bc -l
it fails.

Hi
How about install dateutils ?

datediff 2020-03-04 2020-05-26
83
2 Likes

I recommend to use awk instead of bc to calculate here, because bc displays floating point numbers <1 without a leading zero.

So your command ...

echo "`date -d $expdate +%s` - `date -d $today +%s`)/(24*3600)" |bc -l

becomes ...

awk -vd1="$(date -d "$expdate" +%s)" -vd2="$(date -d "$today" +%s)" '  'BEGIN { printf "%.0f\n",(d1-d2)/(24*3600) }'

I generally recommend $(...) instead of `...` for command substitution since different single quotes can be easily mixed up and easy nesting is only possible with the braces.

Note especially the printf command within awk. It accomplishes the rounding.

To get it into a variable you have to use another command substitution:

varname="$( ... command ... )"

How about

printf "%s\n" $(( ($(printf "%d\n" ${Date1//-} ${Date2//-} | date -f-  +"%s-") 0+43200) / 86400 ))
83

Thanks RudiC,

It works & gives correct value as well.