PHP strtotime without leap-years
Posted
by
Christian Sciberras
on Stack Overflow
See other posts from Stack Overflow
or by Christian Sciberras
Published on 2010-12-24T07:48:30Z
Indexed on
2010/12/24
7:54 UTC
Read the original article
Hit count: 243
With regards to this thread, I've developed a partial solution:
function strtosecs($time,$now=null){
static $LEAPDIFF=86400;
$time=strtotime($time,$now);
return $time-((date('Y',$time)-1968)/4*$LEAPDIFF);
}
The function is supposed to get the number of seconds given a string without checking leap-years.
It does this calculating the number of leap-years 1970 [(year-1986)/4], multiplying it by the difference in seconds between a leap-year and a normal year (which in the end, it's just the number of seconds in a day).
Finally, I simply remove all those excess leap-year seconds from the calculated time. Here's some examples of the inputs/outputs:
// test code
echo strtosecs('+20 years',0).'=>'.(strtosecs('+20 years',0)/31536000);
echo strtosecs('+1 years',0).'=>'.(strtosecs('+1 years',0)/31536000);
// test output
630676800 => 19.998630136986
31471200 => 0.99794520547945
You will probably ask why am I doing a division on the output? It's to test it out; 31536000 is the number of seconds in a year, so that 19.99... should be 20 and 0.99... should be a 1. Sure, I could round it all and get "correct" answer, but I'm worried about the inaccuracies.
© Stack Overflow or respective owner