Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Last Monday - Sunday's dates: Is there a better way?

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.

like image 691
Stomped Avatar asked Mar 09 '10 21:03

Stomped


People also ask

How can I get previous Monday date in PHP?

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


1 Answers

you can use strtotime for this kind of date issues

echo strtotime("last Monday");
like image 130
ahmetunal Avatar answered Oct 20 '22 01:10

ahmetunal