There are some cases where you absolutely cannot import any third party package. One of these instances: online code sandbox websites. After checking ten different Perl sandboxes, I couldn't find a single one that would allow use
statements. Unless you full have system-admin permissions to a Perl environment that's entirely at your whim, even testing any of these answers above will be tricky!
Package-Free Solution
Here is a solution that works works without any package dependencies and remains lightweight and simple...
Full Working Demo
sub getTimeDiff {
my ($times) = @_;
my @times = sort {$a cmp $b} @{$times};
my ($endhour, $endminute, $endsecond, $starthour, $startminute, $startsecond) = (split(':', $times[0]), split(':', $times[1]));
my $diff = ($starthour * 60 * 60) + ($startminute * 60) + ($startsecond) - ($endhour * 60 * 60) - ($endminute * 60) - ($endsecond);
return $diff;
}
print(getTimeDiff(["13:00:00", "13:35:17"])); // output: 2117 (seconds)
Explanation
There are three operations happening here:
- Sort the times using alpha
cmp
sort
, so that the endtime is in the [0]
'th position and the start time in the [1]
'th position.
- Split the start/end times into pieces.
- Calculate the diff using basic arithmetic.
Avoid Package-Based or CPAN-Based Solutions
Why do it this way? Easy, it's not even 1kb of code. Look at some of the file sizes in these packages! That chews through diskspace and memory! If you have something simple to just calculate the time diff, it might be faster to just use your own function.
What's worse than that? Even understanding how these packages work!
use Date::Manip;
$ret = Date::Manip::DateCalc("13:00:00","13:30:00",0).'';
$ret = Date::Manip::DateCalc("00:00:00", $ret,0).'';
$ret = UnixDate($ret, '%I:%M:%S');
print("Date::Manip Result: " . $ret);
According to Date::Manip
, what's the difference between "13:00:00" and "13:30:00"? It should be obvious to everyone!
Date::Manip Result: 12:30:00
So, there are difficulties in these packages with the problem of basic addition. I'm really not sure what else to say.