« Fright? | Main | Obituary Notices »

May 16, 2005

Days Difference in Shell

Question: I want to calculate the number of days between two dates in shell.

Answer: Current versions of ksh can do some magic using printf.

#!/bin/ksh DATE1=`printf '%(%s)Tn' 'Oct 6 07:51:55 2004'` DATE2=`printf '%(%s)Tn' 'May 14 12:00:42 2005'` SECS=`expr $DATE2 - $DATE1` MINS=`expr $SECS / 60` HRS=`expr $MINS / 60` DAYS=`expr $HRS / 24` echo $DAYS

Obviously you can adapt this as required. Remember with expr to keep spaces around the operators...

Posted by Ozguru at May 16, 2005 06:00 AM

Comments

If your version of ksh doesn't support the pretty printf command, you can check this post for a very long and complicated set of functions which will do the same sort of thing. In some ways the functions are more instructive but it is unlikely that you could remember all that to implement on the spot :-)

Of course the real geeks out there will have a library of these functions on a CD-ROM in their toolkit :-)

Posted by: Ozguru at May 16, 2005 12:05 PM

Just got your email about this (and then spotted your comment). I like this solution better - it is (1) more elegant and (2) more flexible. Basically it works by converting stuff into Julian days ( I always wondered why anyone would do Julian date stuff).

Posted by: Rofl at May 16, 2005 12:05 PM

Me! Me! I know an even better answer. Check out SysAdmin Magazine's article which covers how to do it in shell, C and Perl - all three in the one place at the same time. It is a really cool magazine for geeks...

Posted by: Gil at May 16, 2005 12:05 PM