Posts Tagged ‘dates’

PHP: Handle dates and time on php

Today 20010-29-03 i was so curious when i was programming a report in php that print a PDF document, the report take the limits dates between 2 dates with 6 combo box as the picture show  is an easy  way to do that….  the problem result when the requirement of the report is to take one month left from the current month so the first date must be February.  I always use the date and strtotime  to do that with php functions:

date(‘m’,  strtotime(‘-1 months’));

This simple function print the equivalent less numeric one  from the current month (in this case ‘2’ February) witch means that we’re in march, well the problem comes when the day from the current month is more than the before; this year there is not leap year so february only have 28 days (although this problem has nothing to do with this part), and the strtotime function take the current day to do the subtration.  i never see this problem before but this happens too when the current month have 31 days and the month before 30.  so with partner fellow worker on the job we find a solution for this problem:

date(‘m’, mktime(0,0,0,date(‘m’)-1,1));

With this functions we made the subtration of the months but specifying the day in this case the first day, so with this we can avoid this little bug on PHP.  Now you know how to do subtration and how avoid this problem.

For test:

If you want to try in your environment, put the your pc clock on March 29, or October 31  adn you will see what return each functions.

echo ‘mktime: ‘.date(‘m’, mktime(0,0,0,date(‘m’)-1,1));
echo ‘<br />’;
echo ‘strtotime: ‘.date(‘m’, strtotime(‘-1 months’));

For more information:

http://php.net/strtotime

http://www.php.net/mktime

Don’t be afraid to make mistakes beacuse Errors are part of the learning process.