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

Hi Monks, I have two dates in the following order: $date1 = "2014/01/25 23:11:14"; $date2 = "2014/01/26 00:30:37"; I would like to calculate the difference between the two in Minutes & Seconds. Can you suggest how do i go about it? I looked for a few examples and did not find anything as per my requirements. Please advise. Thanks, Bugz

Replies are listed 'Best First'.
Re: Calculating Difference In Dates
by kcott (Archbishop) on Jan 27, 2014 at 23:20 UTC

    G'day Bugz,

    You can use the core modules Time::Piece and Time::Seconds:

    #!/usr/bin/env perl -l use strict; use warnings; use Time::Piece; use Time::Seconds; my $date1 = "2014/01/25 23:11:14"; my $date2 = "2014/01/26 00:30:37"; my $format = '%Y/%m/%d %H:%M:%S'; my $t0 = Time::Piece->strptime($date1, $format); my $t1 = Time::Piece->strptime($date2, $format); my $diff = $t1 - $t0; my $mins = int $diff->minutes; my $secs = $diff - $mins * 60; print "Minutes: $mins"; print "Seconds: $secs";

    Output:

    Minutes: 79 Seconds: 23

    -- Ken

      Thank you Ken.
Re: Calculating Difference In Dates
by choroba (Cardinal) on Jan 28, 2014 at 09:36 UTC
    Using DateTime:
    #!/usr/bin/perl use warnings; use strict; use DateTime; my @dt; for ('2014/01/25 23:11:14', '2014/01/26 00:30:37') { my ($year, $month, $day, $hour, $minute, $second) = split /[^0-9]/ +; push @dt, 'DateTime'->new( year => $year, month => $month, day => $day, hour => $hour, minute => $minute, second => $second, time_zone => 'floating', ); } my %diff = ( $dt[1] - $dt[0] )->deltas; for my $unit (qw(months days minutes seconds)) { print "$unit: $diff{$unit}\n" if $diff{$unit}; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Calculating Difference In Dates
by ambrus (Abbot) on Apr 18, 2014 at 10:35 UTC

    I recommend the Date::Manip module.

    my $date1 = "2014/01/25 23:11:14"; my $date2 = "2014/01/26 00:30:37"; use Date::Manip::Date 6.23; my $do1 = Date::Manip::Date->new($date1); my $do2 = $do1->new($date2); my $delta = $do1->calc($do2); # If you want a human-readable string: print $delta->printf("The difference is %mym minutes, %sss seconds.\n" +); # If you want the number of minutes and seconds as separate numbers: my($delta_min, $delta_sec) = $delta->printf("%mym", "%sss");