Tuesday, October 30, 2007

PHP Date Math with date() and mktime()

Normal date math in PHP does not account for leap years (or apparently Daylight Savings Time for that matter).

If the current month is January, 2008 and you run
$newMonthText = date("F", mktime(0, 0, 0, date("m")+1, date("d"), date("Y")));
you'll get "March" for the value instead of what you probably want, which is "February." The good people on php.net have lots to say about this. (I think the other condition is that "skipping" Feburary happens only on the 30th or 31st of the current month.)

The way to deal with this is to use
$newMonthText = date("F", mktime(0, 0, 0, date("m")+1, 1, date("Y")));
which will return "February" as intended.

No comments: