Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl time parsing and difference calculations for "plus days:hours:minutes"

Tags:

perl

I have a string with a time difference like:

12:03:22  <- where
 ^  ^  ^
 |  |  +minutes
 |  +hours
 +days

Mandatory is only the minutes, hours and days can be omitted, but here can be e.g. 120:30, so 120 hours and 30 minutes.

Need calculate the date and time for NOW + difference, so for example:

when now is "May 20, 13:50" and
the string is "1:1:5"
want get as result: "2012 05 21 14 55" (May 21, 14:55)

I know DateTime, but what is the easy way parsing the input string? I'm sure than here is a better way as:

use _usual_things_;
my ....
if($str =~ m/(.*):(.*):(.*)/) {
   $d = $1; $h = $2; $m = $3;
}
elsif( $str =~ m/(.*):(.*)/ ) {
   $h = $1; $m = $2;
} elsif ($str =~ m/\d+/ ) {
   $m = $1;
}
else {
  say "error";
}

And how to add to the currect date the parsed days, hours, minutes?

like image 356
jm666 Avatar asked Nov 29 '25 16:11

jm666


1 Answers

What about using reverse to avoid checking the format?

my ($m, $h, $d) = reverse split /:/, $str;

To add this to current date, just use DateTime:

print DateTime->now->add(days    => $d // 0,
                         hours   => $h // 0,
                         minutes => $m);
like image 194
choroba Avatar answered Dec 02 '25 07:12

choroba