LinuxQuestions.org

LinuxQuestions.org (http://www.linuxquestions.org/questions/index.php)
-   AIX (http://www.linuxquestions.org/questions/forumdisplay.php?f=43)
-   -   perl date difference: strange behaviour (http://www.linuxquestions.org/questions/showthread.php?t=4175443775)

fritz001 01-02-2013 02:59 AM

perl date difference: strange behaviour
 
#!/usr/bin/perl

use Time::Local;

$da1 = "2012-12-27";
$da2 = "2013-01-02";


@DDATE1 = split(/-/, $da1);
@DDATE2 = split(/-/, $da2);
%months = ( '1', 0,
'2', 1,
'3', 2,
'4', 3,
'5', 4,
'6', 5,
'7', 6,
'8', 7,
'9', 8,
'10', 9,
'11', 10,
'12', 11 );

$DATE1 = timelocal(0, 0, 0, $DDATE1[2], $months['$DDATE1[1]'], $DDATE1[0]);
print "$DATE1\n";
$DATE2 = timelocal(0, 0, 0, $DDATE2[2], $months['$DDATE2[1]'], $DDATE2[0]);
print "$DATE2\n";
$diffSeconds = $DATE2 - $DATE1;
print "$diffSeconds\n";
$diffDays = $diffSeconds / (60 * 60 * 24);
print "$diffDays\n";



i'm getting 341 days !!!!


P.S. I'm talking about UNIX platform: AIX 5.3/6.1 and no additional perl modules can be installed

linosaurusroot 01-02-2013 05:12 AM

You aren't using "perl -w".

Incorrect quoting gets both dates treated with an undefined (0) month.
Quote:

$DATE1 = timelocal(0, 0, 0, $DDATE1[2], $months['$DDATE1[1]'], $DDATE1[0]);
You can skip all the %month thing by using "-1".
Code:

$DATE1 = timelocal(0, 0, 0, $DDATE1[2], $DDATE1[1]-1 , $DDATE1[0]);

fritz001 01-02-2013 05:37 AM

Quote:

Originally Posted by fritz001 (Post 4861081)
#!/usr/bin/perl

use Time::Local;

$da1 = "2012-12-27";
$da2 = "2013-01-02";


@DDATE1 = split(/-/, $da1);
@DDATE2 = split(/-/, $da2);
%months = ( '1', 0,
'2', 1,
'3', 2,
'4', 3,
'5', 4,
'6', 5,
'7', 6,
'8', 7,
'9', 8,
'10', 9,
'11', 10,
'12', 11 );

$DATE1 = timelocal(0, 0, 0, $DDATE1[2], $months['$DDATE1[1]'], $DDATE1[0]);
print "$DATE1\n";
$DATE2 = timelocal(0, 0, 0, $DDATE2[2], $months['$DDATE2[1]'], $DDATE2[0]);
print "$DATE2\n";
$diffSeconds = $DATE2 - $DATE1;
print "$diffSeconds\n";
$diffDays = $diffSeconds / (60 * 60 * 24);
print "$diffDays\n";



i'm getting 341 days !!!!


P.S. I'm talking about UNIX platform: AIX 5.3/6.1 and no additional perl modules can be installed


!!! FIXED !!!

WRONG:: $DATE1 = timelocal(0, 0, 0, $DDATE1[2], $months['$DDATE1[1]'], $DDATE1[0]);

GOOD: $DATE1 = timelocal(0, 0, 0, $DDATE1[2], $months{$DDATE1[1]}, $DDATE1[0]);



I've almost forgot how to access the individual elements of a hash....


All times are GMT -5. The time now is 02:36 AM.