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

what's the best way to find the difference (in minutes) between 2 dates of format $yyyy-$mm-$dd $hh:$min:$ss?

Replies are listed 'Best First'.
Re: difference between 2 dates
by blakem (Monsignor) on Mar 06, 2002 at 11:07 UTC
    Try the nifty new Time::Piece module. It makes this stuff easy.
    #!/usr/bin/perl -wT use strict; use Time::Piece; my $date1 = "2000-11-24 03:23:45"; my $date2 = "2001-01-24 05:45:00"; my $format = "%Y-%m-%d %T"; my $diff = abs (Time::Piece->strptime( $date1, $format ) - Time::Piece->strptime( $date2, $format )); print "There are " . $diff->minutes . " minutes between $date1 and $da +te2\n"; __END__ There are 87981.25 minutes between 2000-11-24 03:23:45 and 2001-01-24 +05:45:00

    -Blake

      I like this ... I didn't realize until now that strptime was set up to return a Time::Piece object and that you could directly subtract one Time::Piece object from another. Very nice. Monk discussion once again proves to be educational.

        Also notice that the subtraction returns a Time::Seconds object rather than a simple integer. This trivialized the "in minutes" requirement, and makes more complicated calculations less error prone.

        -Blake

Re: difference between 2 dates
by toadi (Chaplain) on Mar 06, 2002 at 09:18 UTC
    Best thing to use is: Date::Calc

    --
    My opinions may have changed,
    but not the fact that I am right

Re: difference between 2 dates
by nandeya (Monk) on Mar 06, 2002 at 19:32 UTC
    Here's another way...

    #!/usr/bin/perl -w use strict; use Date::Calc; my ($nwyr,$nwmth,$nwday, $nwhr,$nwmin,$nwsec) = Date::Calc::Today_and_ +Now(); my $dttm1 = "2002-03-06 12:10:52"; my ($d1yr, $d1mth, $d1day, $d1hr, $d1min, $d1sec) = ($dttm1 =~ /(\d*)-(\d*)-(\d*) (\d*):(\d*):(\d*)/); my ($Ddays,$Dhrs,$Dmins,$Dsecs) = Date::Calc::Delta_DHMS($nwyr,$nwmth,$nwday, $nwhr,$nwmin,$nwsec, $d1yr,$d1mth,$d1day, $d1hr,$d1min,$d1sec); my $totMinsDiff = abs(($Ddays * 24 * 60) + ($Dhrs * 60) + ($Dmins) + ( +$Dsecs / 60)); print "Absolute difference in minutes is: $totMinsDiff \n";
    nandeya
Re: difference between 2 dates
by mojotoad (Monsignor) on Feb 05, 2003 at 06:30 UTC