当给定一个日期时,如何在php中获取该周周一的日期

5

1
尝试使用date('w')来获取给定日期是星期几 - 星期一为第1天。之后就只是数学计算了。 - Marc B
同意这个重复的问题,但我更喜欢我的方式 :p - Chris Baker
2个回答

11
function last_monday($date) {
    if (!is_numeric($date))
        $date = strtotime($date);
    if (date('w', $date) == 1)
        return $date;
    else
        return strtotime(
            'last monday',
             $date
        );
}

echo date('m/d/y', last_monday('8/14/2012')); // 8/13/2012 (tuesday gives us the previous monday)
echo date('m/d/y', last_monday('8/13/2012')); // 8/13/2012 (monday throws back that day)
echo date('m/d/y', last_monday('8/12/2012')); // 8/06/2012 (sunday goes to previous week)

尝试这个:http://codepad.org/rDAI4Scr

...或者是一个变种,使星期日返回下一天(星期一),而不是上一周,只需添加一行代码:

 elseif (date('w', $date) == 0)
    return strtotime(
        'next monday',
         $date
    );

试一下:http://codepad.org/S2NhrU2Z

你可以传递一个时间戳或一个字符串,它会返回一个时间戳。

文档


3

使用 strtotime 函数,您可以轻松创建时间戳。该函数接受短语(例如“上周一”)以及辅助参数,您可以使用mktime从您拥有的日期轻松创建时间戳(请注意特定日期的输入为小时、分钟、秒、月份、日期、年份)。

<?php
    $monday=strtotime("monday this week", mktime(0,0,0, 8, 8, 2012));
    echo date("Y-m-d",$monday);
    // Output: 2012-08-06
?>

Editstrtotime中的“上周一”更改为“本周一”,现在可以完美地运行。


2
如果输入日期为2012-08-06,则此方法无法正常工作。 - irrelephant
1
现在已经可以了 :) 顺便加一分,感谢您的敏锐观察 :) - Fluffeh
输出为"2012-08-13" - Chris Baker
@Chris 很有趣,在我的笔记本电脑上运行良好(PHP5.3.0)。 - Fluffeh
@Fluffeh 更奇怪的是...我在自己的服务器上测试了一下,返回的日期是“2012年8月6日”。很难归咎于时区...如果问题日期是星期天,我可以理解,但是星期三向前推一周?你说得对...很奇怪。 - Chris Baker
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接