Date difference using perl

Hi All,

I am using the below code to get the days difference between 2 dates

ddate="05/31/2018"
bdate="06/10/2018"
diff=$(perl -e 'use Time::Local;
my ($month1,$day1,$year1)=split /\W+/, $ENV{'ddate'};
my ($month2,$day2,$year2)=split /\W+/, $ENV{'bdate'};
my $time1 = timelocal($sec1,$min1,$hour1,$day1,$month1,$year1);
my $time2 = timelocal($sec2,$min2,$hour2,$day2,$month2,$year2);
$time = ($time2 - $time1)/86400;
print $time;')
echo $diff

When i try to run the script I get the below error

Day '31' out of range 1..30 at -e line 4

I understand that this is due to the array placement in perl, but i am not sure how to get the script working. Please help on this.

The month range in Time::Local names is from 0 to 11 not from 1 to 12.

See: Time::Local - Day '31' out of range 1..30

Subtract 1 from the month number and it will work. Otherwise you hit the error here that "5" is not May but June, which has 30 Days and causes an error.

Hi,

thanks for the reply.

If i use "-1" with month, then i get the below error.

diff=$(perl -e 'use Time::Local;
my ($month1,$day1,$year1)=split /\W+/, $ENV{'ddate'};
my ($month2,$day2,$year2)=split /\W+/, $ENV{'bdate'};
my $time1 = timelocal($sec1,$min1,$hour1,$day1,$month1-1,$year1);
my $time2 = timelocal($sec2,$min2,$hour2,$day2,$month2-1,$year2);
$time = ($time2 - $time1)/86400;
print $time;')

Month '-1' out of range 0..11 at -e line 4

How do i change the month here ?

-1 is not a valid value vor month either.

You may use "debug prints" in your code to verify the values of the variables.

No. What stomp means is perl uses a zero based month: i.e., January is zero ... so June is 5. perl is based on the standard C library, and timelocal is being supplied with what amounts to a struct tm in the C language.
From the man page:

      struct tm {
               int tm_sec;    /* Seconds (0-60) */
               int tm_min;    /* Minutes (0-59) */
               int tm_hour;   /* Hours (0-23) */
               int tm_mday;   /* Day of the month (1-31) */
               int tm_mon;    /* Month (0-11) */
               int tm_year;   /* Year - 1900 */
               int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
               int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
               int tm_isdst;  /* Daylight saving time */
           };

This is the same thing, almost, as your ($sec, $min, $hour,.....)

Try: Time::Local - perldoc.perl.org

Works OK for me here with the new -1 version:

$ export ddate="05/31/2018"
$ export bdate="06/10/2018"
$ diff=$(perl -e 'use Time::Local;
 my ($month1,$day1,$year1)=split /\W+/, $ENV{'ddate'};
 my ($month2,$day2,$year2)=split /\W+/, $ENV{'bdate'};
 my $time1 = timelocal($sec1,$min1,$hour1,$day1,$month1-1,$year1);
 my $time2 = timelocal($sec2,$min2,$hour2,$day2,$month2-1,$year2);
 $time = ($time2 - $time1)/86400;
 print $time;')
$ echo $diff
10