Tuesday, July 26, 2011

PHP - Is it a leap year?

After spending 20 minutes writing a short function to test a date to see if it is a leap year, I find that php has a built in date function to do the job. Never mind it was interesting anyway to discover that there is a method in the madness of leap years. According to wikipedia, if a year is divisible by 4 it is a leap year. But not if it is divisible by 100, unless it is divisible by 400....get it?

So this was my waste of time leap year calculating function..


<?php
$year = date('Y') ;
if ( $year %400 == 0 ) { $isleap = 'yes' ; }
elseif ( $year %100 == 0 ) { $isleap = 'no' ; }
elseif ( $year %4 == 0 ) { $isleap = 'yes' ; }
else {$isleap='no';}
if ( $isleap == 'yes')
{echo $year." is a leap year";}
else
{echo $year." is not a leap year";}
?>


The smart way to do it though is just with date('L'), this php function returns 1 if it is a leap year and 0 if it is not...much simpler...


<?php
$year=date('Y');
$isleap = date('L') ;
if ( $isleap == '1')
{echo $year." is a leap year";}
else
{echo $year." is not a leap year";}
?>

No comments: