Operating System - Linux
1753428 Members
4770 Online
108793 Solutions
New Discussion юеВ

Re: Perl - calculate time difference

 
Anand_30
Regular Advisor

Perl - calculate time difference

I have to find the time difference between 2 date time of the format 08252005193248 and 08252005193249. The last 6 digits value is that of the time.

I am doing the following:

my $time1 = substr($data[3],9,6);
my $time2 = substr($data[4],9,6);

my $timediff = $time2 - $time1;

if($timediff < 0)
{
$timediff += 60*60*24;
}

But still I am getting time difference in negative.

Please help.

Thanks,
Anand
4 REPLIES 4
Steven E. Protter
Exalted Contributor

Re: Perl - calculate time difference

I recommend a time tested tool, created by A. Clay, our fearless point leader.

http://hpux.ws/merijn/caljd-2.2.pl

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
A. Clay Stephenson
Acclaimed Contributor

Re: Perl - calculate time difference

First of all, substr in Perl unlike awk is zero-based rather than one-based but a much better answer is to convert the entire string to epoch seconds so that differences over days can be calculated.
#!/usr/bin/perl -w


use strict;
use Time::Local;

my $t1 = "08252005194248";
my $t2 = "08252005194249";


sub to_seconds
{
use integer;
my $x = $_[0];

my $mo = substr($x,0,2);
my $day = substr($x,2,2);
my $year = substr($x,4,4);
my $hour = substr($x,8,2);
my $minute = substr($x,10,2);
my $second = substr($x,12,2);

my $t = timelocal($second,$minute,$hour,$day,$mo - 1,$year - 1900);
return($t);
}

my $diff = to_seconds($t2) - to_seconds($t1);
printf("Diff = %d seconds\n",$diff);

If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Perl - calculate time difference

Hi Anand:

Are you running with 'use warnings' or at least '-w' ???

Looking at your code in isolation, this would lead to a negative computation if you data[4] wasn't defined.

Regards!

...JRF...
Hein van den Heuvel
Honored Contributor

Re: Perl - calculate time difference

Like Clay's solution, but using UNPACK to break down the input strings



---------
use Time::Local;

sub seconds {
($mo,$d,$y,$h,$mi,$s) = unpack 'a2a2a4a2a2a2', $_[0];
return timelocal($s,$mi,$h,$d,$mo - 1,$y - 1900);
}
$t1 = seconds (shift @ARGV);
$t2 = seconds (shift @ARGV);

print $t1 - $t2;
------
$ perl tmp.p 08252005194248 08252005184248
3600
$ perl tmp.p 08252005194248 08242005194248
86400

Hein.