Adjust dates by months and years in perl

I recently needed to subtract 1 month from a date for a perl program I was working on. Whilst subtracting days or weeks is easy as you can just convert it to a timestamp, adjusting months or years is far harder due to all the complexity of having to deal with different numbers of days in months, leap years, etc.

Took me a little while to find the best function to use, but there is a perl module that can do this for you called Date::Calc, which provides a function called Add_Delta_YM.

This function will handle all the complexity, and will round to the closet date in the previous month, handling situations like “2007-03-31 – 1 month == 2007-02-28” in a nice fashion.

Below is a code sample:

 #!/usr/bin/perl

 use strict;
 use Date::Calc qw(:all);

 my $year  = "2007";
 my $month = "3";
 my $day   = "31";

 my $Dy    = "0";    # number of years to adjust by
 my $Dm    = "-1";   # number of months to adjust by (-1 means go back 1 month)

 ($year,$month,$day) = Add_Delta_YM($year,$month,$day, $Dy,$Dm);

 print "$year-$month-$day\n";

If you need to do any other type of date manipulation, I suggest you look into the Date::Calc module to see if it fulfills your needs. As an added plus, if your a RHEL/CentOS user the module is available in the base repository.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.