Click to See Complete Forum and Search --> : Remarks on Finding last week's day


Jaelan
01-18-2005, 02:09 PM
Hey guys,
I am trying to determine the last week's monday in the format: month DD, YYYY HH:MM:SS. Thus, I came up with this function:


/******************************************************/
/* GETLASTWEEKDAY *************************************/
/******************************************************/
/* FORMAT: HOW THE DAY IS SUPPOSED TO LOOK ************/
/******************************************************/
function getLastWeekDay($format) {
$day = date("w");

/* SET DATE TO A WEEK AGO FROM THE LAST MONDAY */
switch ($day) {
case '1':
/* MONDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+0)))." 00:00:00");
break;
case '2':
/* TUESDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+1)))." 00:00:00");
break;
case '3':
/* WEDNESDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+2)))." 00:00:00");
break;
case '4':
/* THURSDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+3)))." 00:00:00");
break;
case '5':
/* FRIDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+4)))." 00:00:00");
break;
case '6':
/* SATURDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+5)))." 00:00:00");
break;
case '0':
/* SUNDAY */
$lastWeek = date($format, (time()-(60*60*24*(7+6)))." 00:00:00");
break;
}

return $lastWeek;
}


It's fairly simple, but I was wondering how other people did it, if there is a better way, etc.
I looked at some calendar functions, namely JDDayOfWeek(), but I couldn't come up with a way to use it either without using a switch statement. I tested it for today, it works fine, so I can't think anything other than it working for the other days. But if you guys have a better way, I'm interested.

Jaelan

NogDog
01-18-2005, 02:38 PM
Well, I think I got it down to 2 lines. :)

function getLastWeekDay($format) {
$day = (date('w') == 0) ? 6 : date('w') - 1;
return(date($format, (time()-(60*60*24*(7+$day)))." 00:00:00"));
}

Jona
01-18-2005, 02:39 PM
You function could better be written as:


function getLastWeekDay($format) {
return date($format, (time()-(60*60*24*(7+(date("w")))));
}


You might want to look into the mktime() (http://www.php.net/mktime) function, though.

Edit: NogDog beat me and also caught something I missed.

Jaelan
01-18-2005, 02:42 PM
BRILLIANT!!!

Jaelan

NogDog
01-20-2005, 09:17 AM
Check out the strtotime() function. I just ran across this at http://us3.php.net/manual/en/function.strtotime.php while researching another question:

echo strtotime("last Monday"), "\n";

Jaelan
01-20-2005, 09:21 AM
lol, that's awesome! perfect! :)

and this is why php is cool