Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 995
Goutham Avatar asked Aug 30 '13 05:08

Goutham


People also ask

How do I get the difference between two dates in Perl?

$bree = 361535725; # 16 Jun 1981, 4:35:25 $nat = 96201950; # 18 Jan 1973, 3:45:50 $difference = $bree - $nat; print "There were $difference seconds between Nat and Bree\n"; There were 265333775 seconds between Nat and Bree $seconds = $difference % 60; $difference = ($difference - $seconds) / 60; $minutes = $difference ...

How do I format a date in Perl?

The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign. There are two types of specifiers, one is for local time and other is for gmt time zone.


2 Answers

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;
like image 179
Dave Cross Avatar answered Oct 16 '22 03:10

Dave Cross


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.

like image 20
Ed Heal Avatar answered Oct 16 '22 03:10

Ed Heal