UNIX Date Tool – Tool to Subtract Dates in UNIX

awkdateshellsolarisUtilities

Is there any tool in Solaris UNIX (so no GNU tool available) to subtract dates? I know that in Linux we have gawk that can subtract one date from another. But in Solaris the maximum we have is nawk (improved awk) which cannot perform date calculations. Also I cannot use perl.

Is there any way to do date calculations like 20100909 - 20001010?

UPDATE: Is bc able to perform dates calculations?

Best Answer

Here is an awk script I just wrote up, should work with an POSIX awk. You'll have to try the Solaris version; remember that there are two versions of Awk on Solaris as well, one in /bin and one in /usr/xpg4/bin/awk (which is nawk, I believe).

BEGIN {
    daysofmonth["01"] = 0; daysofmonth["02"] = 31; daysofmonth["03"] = 59;
    daysofmonth["04"] = 90; daysofmonth["05"] = 120; daysofmonth["06"] = 151;
    daysofmonth["07"] = 181; daysofmonth["08"] = 212; daysofmonth["09"] = 243;
    daysofmonth["10"] = 273; daysofmonth["11"] = 304; daysofmonth["12"] = 334;
    fullday = 86400;
}
/[12][09][0-9][0-9][01][0-9][0123][0-9]/ {
    year = substr($0, 1, 4); month = substr($0, 5, 2); day = substr($0, 7, 2);
    date = ((year - 1970) * 365.25) + daysofmonth[month] + day - 1;
    if ((year % 4) == 0 && month > 2) { date = date + 1; }
    print date * fullday - (25200);
}
{}

Pass a YYYYmmdd date string through and it will be converted to number of seconds since the Epoch (with a bit of give for being on day boundaries). Then you will be able to subtract the two.

today=`echo 20110210 | awk -f convdate.awk`
then=`echo 20001231 | awk -f convdate.awk`
sincethen=`expr $today - $then`
Related Question