How to calculate date difference in perl

17,490

Solution 1

Time::Piece has been a standard part of Perl since 2007.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use Time::Piece;

my $date1 = 'Fri Aug 30 10:53:38 2013';
my $date2 = 'Fri Aug 30 02:12:25 2013';

my $format = '%a %b %d %H:%M:%S %Y';

my $diff = Time::Piece->strptime($date1, $format)
         - Time::Piece->strptime($date2, $format);

say $diff;

Solution 2

Convert both dates to UNIX time

See http://metacpan.org/pod/Date::Parse

Then you can do a simple mathematical subtraction to find the number of seconds between the two.

Then it is simple maths all the way to get minutes, hours, etc.

Share:
17,490
Admin
Author by

Admin

Updated on June 12, 2022

Comments

  • Admin
    Admin almost 2 years

    I am a novice in perl scripting. I have a requirement where in I need to find the difference of two dates in the minutes/seconds

    $date1 =  Fri Aug 30 10:53:38 2013
    $date2 =  Fri Aug 30 02:12:25 2013
    

    can you tell me how do we achieve this, Parsing , calculation , modules req and all

    Thanks Goutham

  • Ian Hyzy
    Ian Hyzy over 7 years
    Doing math will not get you the correct answer.
  • ikegami
    ikegami about 4 years
    Time::Piece->strptime is for dealing with UTC times. If dealing with local times, use Time::Piece::localtime->strptime instead.