2009-02-02 58 views

回答

17

我知道已经有一个被接受的答案,但是它不符合要求的第二个要求。在上述情况下,如果在星期三使用,时间将会产生昨天。所以,仅仅是准确的,你仍然需要检查这一点:

$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; 

由于davil在他的评论中指出,这是那种我的一个快速射击。由于夏令时间的限制,以上计算将每年关闭一次。足够好的解决方案是:

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

如果您需要的时间为0:00h,那么您当然需要一些额外的努力。

13

PHP实际上使得这很容易:

echo strtotime('last Tuesday'); 

strtotime文档。

+0

TT为什么我还没有看到,在文档TT 非常感谢我欠你 – lock 2009-02-02 08:39:51

+1

这其实不给你,但最后“最后一周的星期二”星期二(可以是同一周...如果是星期五) – garyee 2015-06-16 08:03:07

+0

正确@garyee - 请检查我的回答低于 – smo0f 2015-08-21 15:14:48

0

您忘记了日期的第二个参数('W',$星期二)的strtotime hmm。

转换$周二时间戳之前 “$周二,7 * 86400 + 7200”

MDE。

3

工作液:

$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); 
1
// 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)) . "\n"; 
} 

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}"); 
} 
0
<?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)); 
?> 
13

大部分答案要么太多,或者技术上不正确,因为“上周二”并不一定意味着从周二上周,它只是意味着上周二,可能在“现在”的同一周内。

正确的答案是:

strtotime('tuesday last week') 
相关问题