找到上个月29日,两个月前的日期等

时间:2016-05-03 12:52:20

标签: php date

我希望找到本月29日,下个月29日,上个月29日的日期等等......

我知道你可以使用这种代码来查找一周中的几天:

$friday_last = date("d/m/Y", strtotime("last Friday"));
$friday_due = date("d/m/Y", strtotime("this Friday"));

是否有类似的方法来查找每个月的某一天(第29天)或者我是否必须使用不同的代码?

3 个答案:

答案 0 :(得分:2)

您需要使用DateTime(),因为这样可以更轻松地使用日期更多。你会注意到我从每个月的第一天开始。因此,当你到达每个月的29日至30日时,由于奇怪的日期开始发生,所以这并没有打破。

echo (new DateTime())->modify('first day of this month')->format("29/m/Y");
echo (new DateTime())->modify('first day of previous month')->format("29/m/Y");
echo (new DateTime())->modify('first day of next month')->format("29/m/Y");

Demo

echo (new DateTime())->modify('first day of this month')->modify('-2 months')->format("29/m/Y");

Demo

答案 1 :(得分:0)

date()strtotime()一起使用将使您在今年内每月获得第29名:

<?php
    for ($i = 1; $i <= 12; $i++) {
        $d = "2016-" . $i . "-29";
        echo "29th of Month $i is: " . date("l", strtotime($d)) . '<br>';
    }
?>

输出:

29th of Month 1 is: Friday
29th of Month 2 is: Monday
29th of Month 3 is: Tuesday
29th of Month 4 is: Friday
29th of Month 5 is: Sunday
29th of Month 6 is: Wednesday
29th of Month 7 is: Friday
29th of Month 8 is: Monday
29th of Month 9 is: Thursday
29th of Month 10 is: Saturday
29th of Month 11 is: Tuesday
29th of Month 12 is: Thursday

答案 2 :(得分:0)

创建一个包含当前和未来11个月第29天的数组(前几个月+1 month替换为-1 month。在此示例中,我使用+1来解释2月问题,即2月份没有出现):

$baseDate = date_create()->modify( 'first day of this month' );
$dates = array();
for( $i = 0; $i<12; $i++  )
{
    $newDate = clone $baseDate;
    $dates[] = $newDate->modify( '+28 days' );
    $baseDate->modify( '+1 month' );
}

问题 - 你可以想象 - 是在二月:

foreach( $dates as $date )
{
    echo $date->format( 'Y-m-d' ).PHP_EOL;
}

将输出:

2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-03-01      <-----
2017-03-29
2017-04-29

如果您想要“29个月的某一天或上个月的某天”这样的结果,请以这种方式修改上述for循环:

for( $i = 0; $i<12; $i++  )
{
    $newDate = clone $baseDate;
    if( $newDate->modify( '+28 days' )->format( 'm' ) != $baseDate->format( 'm' ) )
    {
        $newDate->modify( 'last day of previous month' );
    }
    $dates[] = $newDate;
    $baseDate->modify( '+1 month' );
}

结果:

2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-02-28      <-----
2017-03-29
2017-04-29