For my front page, I have a bit of a problem – I want to offer the archives of the entire month, as well as last month via my ‘static content’ section. Why’s this a problem? You can’t just subtract an arbitrary date from PHP and expect it to work. Today – XX days is not going to work. If you tell PHP to go to last month, it’ll ask ‘how many days’? How do you know how many days are there in a month? Sure, you can actually mktime() to obtain the number of datys last month, then test to see if today’s date is greater than that, and adjust accordingly, but thats horribly involved – it attempts to correct for timezones, daylight savings, et al. This means lots of work. I don’t want to call a bloody 20k subroutine for a single little link on my page!
I’ve opted to use the following code to compute my ‘What have I posted last month’ snippit. Note that I am only testing to see if this month is Janurary, and if so, setting last month to December, and subtracting from the year. Unless we adopt a new form of telling time, it should continue to work fine; even if it is fugly.
This function was originally over 40 lines of codetesting a billion variables and timezones, localtime(), et all, until it dawned on me… I really don’t need anything complex, I don’t want to peg the CPU, and my archive parsing is fairly simple. I said “Screw it. Elegance before overengineering.” Actually, I mumbled a few other words to myself, but that’s unimportant. Here’s what I did:
$thismonth = date(“m”);
// Is it Janurary? Yes? Say hello to last year!
if ( $thismonth == 1) { $year = date (“Y”); $year = $year – 1; $lastmonth = 12; }
// No. Fine, we can deal with that.
else { $year = date(“Y”); $thismonth = date(“m”); $lastmonth = $thismonth – 1; }
// Lets do this thing!
printf (”%4d%02d”,$year, $lastmonth);
That’s it. After hours of contending with every little oddity; I opted for this. Sure, if I wanted date specifics, I’d have to do a bit more, but, for this, it’s perfect. (A humorous subnote – I only created my new MySQL based front end for the front page this month. Last month is null.) ;)