如何在PHP中获取上周(周二或任何其他日期)的日期?

I think its possible but i cant come up with the right algorithm for it.

What i wanted to do was:

If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.

I know there is an accepted answer already, but imho it does not meet the second requirement that was asked for. In the above case, strtotime would yield yesterday if used on a wednesday. So, just to be exact you would still need to check for this:

$tuesday = strtotime('last Tuesday');
// check if we need to go back in time one more week
$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;

As davil pointed out in his comment, this was kind of a quick-shot of mine. The above calculation will be off by one once a year due to daylight saving time. The good-enough solution would be:

$tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;

If you need the time to be 0:00h, you'll need some extra effort of course.

PHP actually makes this really easy:

echo strtotime('last Tuesday');

See the strtotime documentation.

you forgot strtotime for second argument of date('W', $tuesday) hmm.

convert $tuesday to timestamp before "$tuesday-7*86400+7200"

mde.

Working solution:

$z = date("Y-m-d", strtotime("last Saturday"));
$z = (date('W', strtotime($z)) == date('W')) ? (strtotime($z)-7*86400+7200) : strtotime($z);
print date("Y-m-d", $z);
// test: find last date for each day of the week
foreach (array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') as $day) {
    print $day . " => " . date('m/d/Y', last_dayofweek($day)) . "
";
}

function last_dayofweek($day)
{
    // return timestamp of last Monday...Friday
    // will return today if today is the requested weekday
    $day = strtolower(substr($day, 0, 3));
    if (strtolower(date('D')) == $day)
        return strtotime("today");
    else
        return strtotime("last {$day}");
}
<?php 
    $currentDay = date('D');
    echo "Today-".$today = date("Y-m-d");
    echo "Yesterday-".$yesterday = date("Y-m-d",strtotime('yesterday'));
    echo "Same day last week-".$same_day_last_week = date("Y-m-d",strtotime('last '.$currentDay));
?>

Most of these answers are either too much, or technically incorrect because "last Tuesday" doesn't necessarily mean the Tuesday from last week, it just means the previous Tuesday, which could be within the same week of "now".

The correct answer is:

strtotime('tuesday last week')