How to add hours,minutes,seconds in perl

2019-07-18 06:43发布

I am trying to add hours, minutes and seconds in the format

HH:MM:SS

and the hours and seconds seem to be adding correctly, but I am struggling to format the minutes. What I have done is convert the hours/minutes/seconds to seconds, sum them and the reconvert. Here is my code.

 use strict;
 use warnings;


 my @total_sum = qw(10:07:03 01:01:01 02:02:02);

 my ($sum, $hrs, $mins, $sec);

         for my $t (@total_sum) {

                my ($h, $m, $s) = split /:/, $t;

                my $hm = $h*3600;
                my $tm = $m*60;


                $sum = $sum + $hm + $tm + $s;
         }

         $sec = sprintf ("%02d", $sec = $sum%60);
         $mins = int($sum/60);
         $hrs = int($sum/3600);

         print "$hrs:$mins:$sec\n";

What I am getting is:

         13:790:06   instead of 
         13:10:06

标签: perl sum
3条回答
做自己的国王
2楼-- · 2019-07-18 07:18
     $sec = sprintf ("%02d", $sec = $sum%60);
     $mins = int($sum/60);
     $hrs = int($sum/3600);

Minutes is being calculated as the sum divided by 60. 13 hours plus 10 minutes equals 790 minutes. Why not do something similar with $mins as you are doing with $sec? (Take the modulus)

查看更多
爷、活的狠高调
3楼-- · 2019-07-18 07:23

It is usually better to use modules like DateTime or Date::Manip to do this type of arithmetic, but I guess you want to learn how to do this (EDIT: at the most rudimentary level).

Make sure you intialize sum to 0 before your loop. You need to first do a modulo on the minutes before dividing:

$sec = sprintf ("%02d", $sum%60);
$mins = sprintf("%02d", ($sum%3600)/60);
$hrs = int($sum/3600);

EDIT: Once you get into things like time zones and daylight savings, things get very complicated. See this post as an example: Why is subtracting these two times (in 1927) giving a strange result?

查看更多
太酷不给撩
4楼-- · 2019-07-18 07:23

Just use gmtime() and convert input in seconds into what ever readable format you are interested in.

gmtime() ==> Returned values are localized for the standard Greenwich time zone.

Sample code

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($sum);

print "$hour:$min:$sec\n";;

If in your case if $hour > 23, then please use $yday variable. $yday is the day of the year, in the range 0..364 (or 0..365 in leap years.)

For converting into $hour multiply it with 24, ==> $hour = ($yday * 24) + $hour;

It will work if your difference is less than 364 days (or 0..365 in leap years.), But you can still make it work by adding variable ($year-70) into the equation, but it make equation more complicated because of leap years, hope now it's clear how to use it...

查看更多
登录 后发表回答