Operating System - HP-UX
1821981 Members
3168 Online
109638 Solutions
New Discussion юеВ

Date Comparison in Korn Shell

 
SOLVED
Go to solution
Patrick Collins
Occasional Advisor

Date Comparison in Korn Shell

I need to compare two date strings to see if they are more than 300 days different, I have to do this in Korn Shell cause the boss said so. The date strings look like '02/12/04'. I suppose what I really need is a tool or function to convert a date string to Unix seconds and then do my comparisons. Anyone got any clues.
I have miles to go before I sleep
3 REPLIES 3
Elmar P. Kolkman
Honored Contributor

Re: Date Comparison in Korn Shell

I don't know of a solution with ksh itself, unless you want to start real calculation with leap years etc. But with perl it can be done quite simple, using the timegm function.

#!/usr/local/bin/perl
use Time::Local;

print timegm(0,0,0,$ARGV[0],ARGV[1]-1,ARGV[2]);

This will print out the time in seconds sincs 1900. You need to call it with the time splitted. So you call it like this:
SECONDS=$(timesec.pl `echo $DATE1 | tr '/' ' '`)

Then it's only a matter of comparing the seconds. You could of course do it all in perl...
Every problem has at least one solution. Only some solutions are harder to find.
Graham Cameron_1
Honored Contributor

Re: Date Comparison in Korn Shell

There is a contributed script to do this.
I think shell and perl versions are available.

Go here...
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=13505

-- Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Date Comparison in Korn Shell

Here's the way to do this although you will need the latest version (2.22) of caljd.sh to correctly interpret 2-digit years. Without the -C option year 04 would mean 4 CE rather than 2004 CE. We will turn those dates into Julian Days (days since Jan. 1, 4713 BCE) and then the comparisons are trivially easy.

DT1="02/12/04"
DT2="12/31/05"
JDATE1=$(caljd.sh -S "/" -c -C ${DT1})
JDATE2=$(caljd.sh -S "/" -c -C ${DT2})
DIFF=$(( ${JDATE2} - ${JDATE1} ))
if [[ ${DIFF} -gt 300 ]]
then
echo "More than 300 days"
else
echo "They ain't"
fi

Invoke as caljd.sh -u for full usage. If you like, you could simply yank out the cal_jdate function and use it in your own script but you would then have to parse the date into month, day, and 4-digit year.

If it ain't broke, I can fix that.