获取给定的一组日期时间的第一个星期一

时间:2013-08-04 08:25:28

标签: php datetime

我需要什么

我有一定的日期时间列表。我希望得到每个日期时间的第一个星期一。

例如:假设给定的日期时间是

 2013-07-05 2013-08-05, 2013-09-13 etc.

我希望获得所有这些日期时间的第一个星期一,以便输出结果为

 2013-07-01, 2013-08-05, 2013-09-02 respectively

我实际上是使用stftime来解决这个问题。

strftime("%d/%m/%Y", strtotime("first Monday of July 2012"));

5 个答案:

答案 0 :(得分:8)

使用php Datetime类:

$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
    $test = new DateTime($Date);
    echo $test->modify('first monday')->format('Y-m-d');
}

答案 1 :(得分:0)

<?php
function find_the_first_monday($date)
{
    $time = strtotime($date);
    $year = date('Y', $time);
    $month = date('m', $time);

    for($day = 1; $day <= 31; $day++)
    {
        $time = mktime(0, 0, 0, $month, $day, $year);
        if (date('N', $time) == 1)
        {
            return date('Y-m-d', $time);
        }
    }
}

echo find_the_first_monday('2013-07-05'), "\n";
echo find_the_first_monday('2013-08-05'), "\n";
echo find_the_first_monday('2013-09-13'), "\n";

// output:
// 2013-07-01
// 2013-08-05
// 2013-09-02

答案 2 :(得分:0)

第一个星期一将在一个月的前7天内, DAYOFWEEK(date)返回1 =星期日,2 =星期一,依此类推

也看到了#23的黑客攻击 http://oreilly.com/catalog/sqlhks/chapter/ch04.pdf

答案 3 :(得分:0)

我知道这是一个老问题,我的回答不是这个问题的 100% 解决方案,但这对某人可能有用,这将给出“给定年/月的第一个星期六”:

date("Y-m-d", strtotime("First Saturday of 2021-08")); // gives: 2021-08-07

您可以通过多种方式进行操作。

显然你可以输入“年月的第二个星期六”,它也会找到。

适用于 PHP 5.3.0 及更高版本(在 https://sandbox.onlinephpfunctions.com/ 测试)。

答案 4 :(得分:-1)

您可以遍历日期数组,然后在第一次遇到星期一时退出循环并返回$Date

PHPFIDDLE

$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');

foreach ($Dates as $Date)
{
    $weekday = date('l', strtotime($Date));
    if($weekday == 'Monday') { 
        echo "First Monday in list is - " . $Date;
        break; 
    }
}

输出

First Monday in list is - 2013-08-05

相关问题