Thursday, May 01, 2008

Yet another time calculation in Perl

This is specifically for a delegate I am teaching right now. If I understand the requirements correctly, we hae two times in HH:MM:SS format and we wish to calculate the difference. I know, what if the times are on different days? No answer was given to that one, so I have assumed they are on the same day (today, to be exact).
This will probably change because the specification is a bit "wooly".


use strict;
use warnings;
use Time::Local;

sub str2time
my $in = shift;
my ($hour, $min, $sec) = split (/:/, $in);
my ($mday,$mon,$year) = (localtime(time))[3,4,5];
my $retn;

# timelocal throws an exception on an invalid date/time
eval {
$retn = timelocal($sec,$min,$hour,$mday,$mon,$year);

return $retn; # undef on error

print "Please enter the first time in HH:MM:SS format: ";
my $intime = <STDIN>;
chomp $intime;

my $time1 = str2time($intime);

die "Invalid time: $intime\n" if !defined $time1;

print "Please enter the 2nd time in HH:MM:SS format: ";
$intime = <STDIN>;
chomp $intime;

my $time2 = str2time($intime);

die "Invalid time: $intime\n" if !defined $time1;

my $diff;
if ( $time1 > $time2 ) {
$diff = $time1 - $time2
else {
$diff = $time2 - $time1

my $mins = int($diff / 60);
my $hours = int($mins / 60);
$mins = $mins - ($hours * 60);
my $secs = $diff - ($mins * 60);

printf "Difference: %02d:%02d:%02d\n", $hours,$mins,$secs;

No comments: