Goutham
Goutham

Reputation: 93

How to calculate date difference in perl

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

Upvotes: 7

Views: 19127

Answers (2)

Ed Heal
Ed Heal

Reputation: 60037

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.

Upvotes: 2

Dave Cross
Dave Cross

Reputation: 69314

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;

Upvotes: 15

Related Questions