23-02-2011

Perl date comparison example yyyymmdd

This Perl subroutine calculates and returns the amount of days between two yyyymmdd formatted dates:

use Time::Local 'timelocal_nocheck';
 
 
 
sub day_diff {
 
  # Determine the number of days between two dates in YYYYMMDD format
 
  my $year;
  my $month;
  my $day;
  my $time1;
  my $time2;
 
  $year = substr($_[0], 0, 4);
  $month = substr($_[0], 4, 2);
  $day = substr($_[0], 6, 2);
  $time1 = timelocal_nocheck(0, 0, 0, $day, $month - 1, $year);  # Convert date to seconds from epoch
  $year = substr($_[1], 0, 4);
  $month = substr($_[1], 4, 2);
  $day = substr($_[1], 6, 2);
  $time2 = timelocal_nocheck(0, 0, 0, $day, $month - 1, $year);
  return abs($time1 - $time2) / 86400;
}
 
$diff= &day_diff('20060101','20090101');
 

Comments:

Your comment:

»

 

[x]