Operating System - HP-UX
1833582 Members
3875 Online
110061 Solutions
New Discussion

Difference between two dates?

 
SOLVED
Go to solution
John Wolfe_1
Advisor

Difference between two dates?

Hello Experts,

Is there an easy way to determine in a script the number of days between two dates?

TIA, John W.
At least I have a job.
5 REPLIES 5
Jeff Schussele
Honored Contributor

Re: Difference between two dates?

This is a job for CalMan!
Here he comes to save the day....pun intended :~)

Jeff
PERSEVERANCE -- Remember, whatever does not kill you only makes you stronger!
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Difference between two dates?

Hi John:

Yes, this is about as easy as it gets:

#!/usr/bin/sh

DT1="12 30 1900"
DT2="12 31 2005"

DIFF=$(($(caljd.sh ${DT2}) - $(caljd.sh ${DT1})))
echo "${DT1} and ${DT2} differ by ${DIFF} days."

Note, that this method will work across huge date ranges which lie outside the range of epoch seconds.


You can also use the Date::Calc Perl module.

You can do a caljd.sh -u for full usage.


Regards, Clay



If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Difference between two dates?

Hi again John:

You see that little button that is labeled 'Search'. You probably should have used it first and searches for something like 'date' and 'differnece' and I suspect that you would have found a few hits.

If it ain't broke, I can fix that.
David Lodge
Trusted Contributor

Re: Difference between two dates?

Eek!

Good luck... This is probably one of the few areas where perl would actually be better than shell/awk!

As a way of abusing this - it depends on the date format, if it's saved as 'date +%j' format it is easy:

$ date +%j
200
[100 days later]
$ date +%j
300

If it's done using the normal date format, then that makes it harder. *even* harder if it breaches a) the month and b) the year boundary.

Here is an attempt; I don't expect it to work first time :-)

----------------

#!/usr/bin/sh
# $1 = date in dd/mm/yyyy
function numdays
{
integer day=${1%%/*}
typeset month=${1%/*}
integer month=${month#*/}
integer year=${1##*/}

integer days=${day}
# now we need to work out the amount of dates in the year
while (( month > 1 ))
do
days=$(( ${days} + $(cal ${month} ${year}| awk 'BEGIN {RS="\\n"} {print NF}') ))
month=$(( ${month} - 1 ))
done
}

First=$(numdays 12/04/2002)
Second=$(numdays 10/02/2002)

print (( Second - First ))

----------------

Doing the years is left as an exercise to the reader :-)

HTH

dave
SHABU KHAN
Trusted Contributor

Re: Difference between two dates?