date comparison in bash

Hi

I have this simple script:

#!/bin/bash
date1=2009:07:15:12:36
date2=2009:07:15:12:16

echo $date1
echo $date2

datediff=
#datediff=date1-date2
echo datediff is$datediff

How do i return the difference in seconds?

you seem to have missed 1 field
the correct format should be

YYYY:MM:DD:HH:mm:ss

or you wanted this only?

---------- Post updated at 03:36 PM ---------- Previous update was at 03:05 PM ----------

Try:
Since you wanted the diff in sec, I have left it in sec.
for the condition when the years are diff, you will have to add the condition.

#!/bin/bash

timeCalc()
{
   (( _diff = ($1*3600+$2*60+$3) - ($4*3600+$5*60+$6) ))
   return ${_diff}
}

date1=2009:07:15:12:36
date2=2009:07:15:12:16

echo $date1
echo $date2

_date1=$(echo $date1|awk -F":" '{print $1" "$2" "$3}')
_date2=$(echo $date2|awk -F":" '{print $1" "$2" "$3}')
_time1=$(echo $date1|awk -F":" '{$6==""?$6=0:$6=$6;print $4" "$5" "$6}')
_time2=$(echo $date2|awk -F":" '{$6==""?$6=0:$6=$6;print $4" "$5" "$6}')

dateDiff=$(datecalc -a ${_date1} - ${_date2})

if [[ $dateDiff -eq 0 ]]; then
   timeCalc ${_time1} ${_time2}
fi
echo Diff in second is ${_diff} sec.

PS: datecalc you will have to get from unix.com

Looks good. Where do i find this datecalc method?

hmm this datecalc return an error bin/datecalc[204]: print: bad option(s)

I have not changed a thing?

---------- Post updated at 07:57 AM ---------- Previous update was at 07:54 AM ----------

I also need to know the diff in year, month and seconds. I think it only displays the diff time in seconds?

It works for me... See if it is copied properly

---------- Post updated at 06:32 PM ---------- Previous update was at 06:31 PM ----------

I wrote that in my comment, :slight_smile: You can print that with year, month diff getting from datecalc

I got it to work as well. Thanks!