This will probably change because the specification is a bit "wooly".
#!/usr/bin/perl
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:
Post a Comment