当给出日期时如何在php中获取该周的星期一的日期

Yas*_*tha 4 php datetime date

可能重复:
获取PHP中的第一天?

当给出日期时,我应该得到那个星期一的星期日.

当2012-08-08被授予时,应该返回2012-08-06.

Chr*_*ker 10

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)
Run Code Online (Sandbox Code Playgroud)

试试吧:http://codepad.org/rDAI4Scr

......或者是在第二天(星期一)而不是前一周星期日返回的变体,只需添加一行:

 elseif (date('w', $date) == 0)
    return strtotime(
        'next monday',
         $date
    );
Run Code Online (Sandbox Code Playgroud)

试试吧:http://codepad.org/S2NhrU2Z

你可以传递时间戳或字符串,你会得到一个时间戳

文档


Flu*_*feh 3

您可以使用该函数轻松创建时间戳strtotime- 它接受诸如“上周一”之类的短语以及辅助参数,该辅助参数是您可以从您使用的日期轻松创建的时间戳mktime(请注意,特定日期的输入是Hour,Minute,Second,Month,Day,Year)。

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

编辑将“上周一”更改strtotime为“本周周一”,现在效果很好。

  • 如果输入日期是 2012-08-06,则此方法不起作用。 (2认同)