devslashneil has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

If i have two scalars containing a string similar to "foo 12:23 bar", what's the best way to check if the two time's are within 3 hour's of each other.
ie 12:23 and 13:30 would be true.
Any help would be much appreciated
Regards


Neil Archibald

2006-03-21 Retitled by planetscape, as per Monastery guidelines
Original title: 'Date Question'

  • Comment on Extract times from strings and compute difference

Replies are listed 'Best First'.
Re: Extract times from strings and compute difference
by Tanktalus (Canon) on Jan 22, 2005 at 04:02 UTC

    Neil,

    A bit more precision may be wise in your request. While sgifford's response is possibly sufficient, it doesn't take into account things like day roll-overs. If you don't need to worry about boundary cases such as 23:00 vs 01:00, that's great. If you do need to worry about those cases, then you'll need to give more information about how you can tell (from a human perspective if you can't describe it in perl). For example, the time difference between 23:00 and 01:00 could be 2 hours, or 22 hours, depending on which comes first. If the second time is always later than the first, then that's information we can use to come up with a more accurate algorithm.

    Thanks,

Re: Extract times from strings and compute difference
by davido (Cardinal) on Jan 22, 2005 at 05:37 UTC

    First, tease the time out of the string. Then use Date::Manip's DateCalc() subroutine to compare the two dates, or use the Date::Calc module (probably faster and more targeted to your need).


    Dave

Re: Extract times from strings and compute difference
by sgifford (Prior) on Jan 22, 2005 at 03:40 UTC
    # No error checking ($s1,$s2)=@ARGV; print ((abs(minutes($s1)-minutes($s2)) <= 3*60) ? "yes\n" : "no\n"); sub minutes { my($str)=@_; if ($str =~ /(\d+):(\d+)/) { return $1*60+$2; } return undef; }