3

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?

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

3 Comments

GREAT! :) acepting in 3 minutes! :)
the only flaw: when the $d comes undefined (e.g. for string 2:30) the DateTime complains The 'days' parameter (undef) to DateTime::Duration::new was an 'undef', which is not one of the allowed types:
OK, add // 0 after $d and $h in the addition. (Reply updated)
-1

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" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.