perl and time

D

Drunken Canadian

Ok this may be a noob question but it almost 6am and the coffiee is no
longer working ......

time A = 00:01:04
time b = 0:0:58

how can i add the two times to be 00:02:02?
I know the format is not the same but that is what im stuck with....
 
G

Gunnar Hjalmarsson

Drunken said:
time A = 00:01:04
time b = 0:0:58

how can i add the two times to be 00:02:02?

sub addtime {
my @t1 = split /:/, shift;
my @t2 = split /:/, shift;
my $sec = ($t1[0]+$t2[0])*3600 +
($t1[1]+$t2[1])*60 + $t1[2]+$t2[2];
sprintf '%02d:%02d:%02d', (gmtime $sec)[2,1,0]
}

print addtime('00:01:04', '0:0:58'), "\n";
 
J

John W. Krahn

Drunken said:
Ok this may be a noob question but it almost 6am and the coffiee is no
longer working ......

time A = 00:01:04
time b = 0:0:58

how can i add the two times to be 00:02:02?
I know the format is not the same but that is what im stuck with....

$ perl -e'
$a = "00:01:04";
$b = "0:0:58";
printf "%10s%10s\n", $a, $b;

$x = 2; $d += $_ * 60 ** $x-- for $a =~ /\d+/g;
$x = 2; $e += $_ * 60 ** $x-- for $b =~ /\d+/g;
printf "%10s%10s\n", $d, $e;

$c = $d + $e;
printf "%02d:%02d:%02d\n", reverse $c % 60, int($c /= 60) % 60, int($c /= 60)
% 60;
'
00:01:04 0:0:58
64 58
00:02:02


John
 
G

Gunnar Hjalmarsson

Gunnar said:
Drunken said:
time A = 00:01:04
time b = 0:0:58

how can i add the two times to be 00:02:02?

sub addtime {
my @t1 = split /:/, shift;
my @t2 = split /:/, shift;
my $sec = ($t1[0]+$t2[0])*3600 +
($t1[1]+$t2[1])*60 + $t1[2]+$t2[2];
sprintf '%02d:%02d:%02d', (gmtime $sec)[2,1,0]
}

print addtime('00:01:04', '0:0:58'), "\n";

Or why not shorten the sub to:

sub addtime {
my $sec;
while (@_) {
my @t = reverse split /:/, shift;
$sec += $t[$_]*60**$_ for 0..2;
}
sprintf '%02d:%02d:%02d', (gmtime $sec)[2,1,0]
}

;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top