[Phpwm] More strtotime() fun

David Edwards revlob at gmail.com
Mon Dec 31 15:53:54 GMT 2007


Here's something slightly related to New Year's for you all:

Now, I've groaned on here about this function before (regarding its
North American-centric approach to six-figure date interpretation),
but have today found another fairly serious flaw in its operation. I
found that since PHP5 (the manual page has the exact version number),
asking for a relative date string such as "last monday" returns the
timestamp for midnight on the specified date. This is dead useful when
interacting with timestamps in databases, and working out how many
orders/comments/whatever happened today, or this week, etc.

For example:

$today_start = strtotime("today");
$yesterday_start = strtotime("yesterday");
$this_week_start = strtotime("-1 monday");
$last_week_start = strtotime("-2 monday");

However, running neither of the last two examples are inclusive,
meaning if you ask for "-1 monday" on a Monday you'll get LAST week,
instead of today, potentially giving you up to eight days difference,
instead of seven. I'm prepared to live with my very loose and
occasionally inaccurate definitions of week-starts for now though.

Months get somewhat more interesting, as asking for "last month"
returns the previous month, but with the current date (e.g. asking
fore "last month" on July the 4th returns the timestamp for June the
4th. I thought you could get around it like this:

$this_month_start = strtotime("1 " . date("F Y"));
$last_month_start = strtotime("1 " . date("F Y", strtotime("last month")));

This is where things start to break down, as I noticed today, which
happens to be the 31st of December. Asking for "last month" today
gives me the 1st of December, presumably because the 31st of November
doesn't exist. Having a quick read of the comments on the php.net
manual page, I can see that it is a problem others have encountered
before, and someone has posted quite a good solution using mktime(),
which I might use, but it's a little messy.

Before I start hacking things up, does anyone know of any particularly
good solutions for relative date calculations that might help me?

Happy New Year's to PHPWM!

--
Dave



More information about the Phpwm mailing list