views:

129

answers:

2

Hi, I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this:

WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY))

to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this:

$i = 0; 
while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") { 
  $i++; 
}

$start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y')));
$end_date  = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y')));

This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date.

My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks.

Edit

Apparently, there is:

$start = date('Y-m-d',strtotime('last monday -7 days'));
$end   = date('Y-m-d',strtotime('last monday -1 days'));

That's about a million times more readable. Thank you.

+6  A: 

you can use strtotime for this kind of date issues

echo strtotime("last Monday");
marvin
Elegant! I had forgotten about this.
Vilx-
`echo date('Y-m-d',strtotime('last monday -7 days'));` Mind boggling.
Stomped
+1  A: 

Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division.

Actually, PHP had a Date class in its PEAR library which did exactly this.

Vilx-