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

I am trying to compare two dates. I have to check if there is more than 72 hour difference between the two. Can anyone suggest me how i can implement this.... Thanks in advance

Replies are listed 'Best First'.
Re: Comparing Dates
by Fletch (Bishop) on Mar 13, 2006 at 19:18 UTC
    print "$date_a\n$date_b\n"; print "Do these dates differ by more than 72 hours? "; my $ans = <>; my $differ_by_more_than_72; if( $ans =~ /[Yy][Ee][Ss]/ ) { $differ_by_more_than_72 = 1; } else { $differ_by_more_than_72 = 0; }

    Of course if you'd given more information like what format your input dates are in someone might could give you a slightly better answer, but other than the above you're probably just going to get pointers at some Date module on CPAN.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Comparing Dates
by izut (Chaplain) on Mar 13, 2006 at 19:39 UTC

    Check Date::Manip or Date::Calc, but don't expect they will solve your homework.

    Igor 'izut' Sutton
    your code, your rules.

Re: Comparing Dates
by Miguel (Friar) on Mar 14, 2006 at 01:46 UTC
    This might do the work:
    #!/usr/bin/perl -w use strict; print CompareDates( { DATE_1 => "01/10/2006 4:39:11 PM", DATE_2 => "02/10/2006 4:39:11 PM", LIMIT => 72, # Hours PATTERN => '%d/%m/%Y %l:%M:%S %P' # Optional } ); print CompareDates( { DATE_1 => "01/10/2006 4:39:11 PM", DATE_2 => "04/10/2006 4:39:11 PM", LIMIT => 72, # Hours } ); print CompareDates( { DATE_1 => "01/10/2006 4:39:11 PM", DATE_2 => "06/10/2006 4:39:11 PM", LIMIT => 72, # Hours } ); sub CompareDates { my $params = shift; use DateTime::Format::Strptime; my $parser = DateTime::Format::Strptime->new( pattern => $params->{PATTERN} || '%d/%m/%Y %l:%M:%S %P' ); my $dt1 = $parser->parse_datetime($params->{DATE_1}); my $dt2 = $parser->parse_datetime($params->{DATE_2}); my $dtchk = $dt2->subtract(hours=>$params->{LIMIT}); my $pref = "The difference between '$params->{DATE_1}' AND '$params->{DATE_2}' is"; my $suf = "$params->{LIMIT} hours.\n"; return "$pref bigger than $suf" if ($dtchk > $dt1); return "$pref equal to $suf" if ($dtchk == $dt1); return "$pref smaller than $suf" if ($dtchk < $dt1); }
    Prints:
    The difference between '01/10/2006 4:39:11 PM' AND '02/10/2006 4:39:11 PM' is smaller than 72 hours. The difference between '01/10/2006 4:39:11 PM' AND '04/10/2006 4:39:11 PM' is equal to 72 hours. The difference between '01/10/2006 4:39:11 PM' AND '06/10/2006 4:39:11 PM' is bigger than 72 hours.