We recently brought you the touching story of Shaun, and his coworker's mistaken belief that Perl has no built-in methods for working with dates. Well, Shaun can rest easy: he's not alone.
Apparently, PHP can't handle dates either.
Whether you're Shaun or Chris M, working for an email-marketing company whose clients needed some tweaks to their software integration, inheriting a codebase is always the same: like inheriting a teetering cliffside mansion from your eccentric grand-uncle, the hair on the nape of your neck seems to tickle as you reach for the doorknob. Something primordial reaching up into your consciousness, warning you. But you always go in, despite the horror doubtlessly lurking inside... Chris had just finished recovering from exposure to a custom, PHP-delimited file importer when he received his new inheritance from a fellow consultant. Among the first things Chris learned from inspecing the code was that, if you abuse a database long enough, you can force it to reveal the next 31 days.
First, insert dates into a database table:
INSERT IGNORE INTO Dates (Dates) VALUES
(DATE_ADD(CURDATE(), INTERVAL+1 DAY));
;
INSERT IGNORE INTO Dates (Dates) VALUES
(DATE_ADD(CURDATE(), INTERVAL+2 DAY));
;
INSERT IGNORE INTO Dates (Dates) VALUES
(DATE_ADD(CURDATE(), INTERVAL+3 DAY));
;
...<snip>...
INSERT IGNORE INTO Dates (Dates) VALUES
(DATE_ADD(CURDATE(), INTERVAL+32 DAY));
;
Then, select the next 31 days and their difference from the current date, so we can iterate over them back in PHP Land - a benighted, backwards place where not a single tool to manipulate a date has ever been even theorized.
$sql=<<<SQL
SELECT Dates, DATEDIFF(Dates, CURDATE()) AS `datediff`
FROM Dates
WHERE DATEDIFF(Dates, CURDATE()) < 32 AND DATEDIFF(Dates, CURDATE()) > -1 ;
SQL;
$result = $db->query($sql);
while ($row = $result->fetch()) {
...<snip>...
}
His mind left fragile by its tango with the previous PHP perversion, Chris pulled a colleague in to make sure the above wasn't some sort of hallucination. The other developer offered that perhaps the code's author had understood SQL better than PHP. While Chris appreciated the effort, the thirty-two INSERTs into the same field in the same table made that justification seem unlikely. But it did make him feel better enough to replace the lot with this, leaving the poor database to nurse its wounds in peace:
for ($i = 0; $i <= 31; $i++) {
$date = date('Y-m-d', strtotime("+$i days"));
...<snip>...
}
Remember, developers: before you reach for the Swiss Army knife of your nearest database, do poor Chris and Shaun a favour and consider that your programming language of choice just might be able to do things with dates all by itself.