calculating difference of times

Matthew Seaman matthew at FreeBSD.org
Fri Jul 27 13:02:38 UTC 2012


On 27/07/2012 13:34, Matthias Apitz wrote:
> Do we have something (in the ports) to calculate easy the difference of
> two times given as hh:mm - hh:mm? Some hack in bc(1) or something like
> this? Well, I could translate the times into UNIX seconds of epoche,
> build the diff and reconvert, but something more easy (and not in Perl
> or C, just shell); thanks

Not as such.  Generic toolkits for doing time differences are fairly
common, but they tend to be a) quite large and b) written in higher
level languages than shell.  However they usually account for all the
annoying corner cases like switching to daylight savings time.

If your times are always going to be strictly hh:mm (24h clock) and you
aren't worried about time differences over more than one day, then
something like this in shell:

t1=08:12
t2=12:08

h1=${t1%:*}
h2=${t2%:*}

m1=${t1#*:}
m2=${t2#*:}

mdelta=$(echo "$h2 * 60 + $m2 - $h1 * 60 - $m1" | bc)
hdelta=$(( $mdelta / 60 ))
mdelta=$(( $mdelta % 60 ))
tdelta=printf "%02d:%02d" $hdelta $mdelta"

This will calculate the duration from 23:59 to 00:01 as -23:58; ie. it
assumes both times are on the same calendar day.  Coming up with the
answer 00:02 is left as an exercise for the student.

	Cheers,

	Matthew

-- 
Dr Matthew J Seaman MA, D.Phil.
PGP: http://www.infracaninophile.co.uk/pgpkey


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 267 bytes
Desc: OpenPGP digital signature
Url : http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20120727/ff9050c2/signature.pgp


More information about the freebsd-questions mailing list