mootools php faith camera linux


First day and Last
day of Month with
PHP's mktime()

Okay, I'll get right to the solution:

$lastmonth_start date('Y-m-d',mktime(1,1,1,$m-1,1,date('Y')));
$lastmonth_end date('Y-m-d',mktime(1,1,1,$m,0,date('Y')));

So what's that all about? It is based of PHP's mktime() function, but it also makes use of the ever omnipresent PHP date() function, which one should never leave home without!

Originally as I wrote this out I thought that since date() returns a string , that I might need to force it into an integer. So my solution started out like this:

= (integer) date('n');
$lastmonth_start date('Y-m-d',mktime(1,1,1,$m,1,date('Y')));
$lastmonth_end date('Y-m-d',mktime(1,1,1,++$m,0,date('Y')));

Yeah, that ++ , pre-incrementer is sexy, isn't it? Anyway, I realized that what I needed was not last month, but this month, and then I could use simple math inline to ask for the 1st day of last month:


And the most unintuitive part is where we send in zero, 0 as the argument for the day of the month in the definition of $lastmonth_end :


The $m variable is set to this month, but zero causes the month (and year if applicable) to be "backed up" by a single day...the last day of the previous month!

Last Updated: 2010-08-11 18:39:27
Creative Commons License Jay Johnston is a Zend Certified Engineer in PHP 5 LPI-ID: LPI000102450, Verfication Code: wmnnt56y2k  ... Jay Johnston is certified as LPIC-1 by the Linux Professional Institute