clt60
clt60

Reputation: 63932

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

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?

Upvotes: 3

Views: 811

Answers (2)

choroba
choroba

Reputation: 241918

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);

Upvotes: 8

tuxuday
tuxuday

Reputation: 3037

Parsing can be done once, but branching based on no. of tokes can't be avoided. Here is the sample implementation.

$Str = '12:03:22' ;

@Values = ($Str=~/\G(\d\d):?/g) ;

print "error with input" if not @Values;

if( @Values == 3) { print "Have all 3 values\n" }
elsif( @Values == 2) { print "Have 2 values\n" }

Upvotes: -1

Related Questions