2

我需要什么

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

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

 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"));
4

5 回答 5

8

使用 php 日期时间类:

$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');
}
于 2013-08-06T11:16:55.550 回答
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
于 2013-08-04T08:48:07.560 回答
0

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

另请参阅 hack#23 http://oreilly.com/catalog/sqlhks/chapter/ch04.pdf

于 2013-08-04T08:53:49.493 回答
0

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

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

您可以通过多种方式操纵它。

显然,您可以输入“年月的第二个星期六”,它也会发现。

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

于 2021-07-03T12:15:47.293 回答
-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

于 2013-08-04T09:16:08.283 回答