http://www.perlmonks.org?node_id=1056671


in reply to perl basic count days between two dates

There are modules that will do this for you. I acknowledge you indicate you do not wish to use a module.

So the first step is to figure out the algorithm you wish to use. Grab pencil and paper (or a whiteboard for you youngins), and start trying to figure out how you would do the math by hand.

Then try to write code that would do the same thing you did by hand.

The number of things you are likely to overlook or get wrong are controllable in this example, but high enough to reward your use of a Module where someone else (or several someone elses) took the time to iron out the bugs for you.

But if you just gotta write the code yourself, Step 1 is to figure out how to do it by hand.

P.S. I would suggest researching Leap Year Rules. Assuming your needs do not extend to earlier than Friday, October 15, 1582 in Catholic countries, 1698 or 1752 in principalities headed by Protestants, or 1918 in Russia, a shortcut to use only the modern computation should suffice.

In that computation, the base assumption is that every year has 365 days unless it is declared to be a leap year, in which case it has 366.

More specifically, February would have 29 days rather than the hard-coded 28 you presume in your code.

Research the Leap Year Rules, and you should be able to devise a subroutine which can determine if any given year is a leap year.

From there, you should have all the tools you need to compute number of days between dates, given sufficient forethought to the construction of either your computational algorithms, or your foreach loops -- or some combination thereof.

Update: Okay, fine, here's one example of the many things a module could do for you that you would have to grind through to do by hand:

sub isLeapyear { my ($year, @extraStuff) = @_; if (!defined $year) { $year = 0; } my $leapYearFlag = 0; # Assume not a leap year until proven + otherwise. if ($year % 4) { # Not divisible by 4. Cannot be a leap year. $leapYearFlag = 0; } else { # Divisible by 4. Possibly a leap year. if ($year % 100) { # Is not divisible by 100. It is a leap year. $leapYearFlag = 1; } else { # Is divisible by 100. May not be a leap year. if ($year % 400) { # Is not divisible by 400. Cannot be a leap year. $leapYearFlag = 0; } else { # Is divisible by 400. IS a leap year. $leapYearFlag = 1; } } } return $leapYearFlag; }