dougu4704 2016-04-13 21:56
浏览 23
已采纳

使用PHP查找每月的第n个X天,它总是正确的吗?

OK, I've put together some code which, in this particular case, finds the second (2nd) Sunday of every month depending on whether or not you're before or after it (specifically at 5:00PM that day).

<?php
    $count = 0;
    for( $i = 1 ; $i <=30 ; $i++ )//30 is much more than is needed
    {
        $date = date_create_from_format('Y-m-d H:i:s',date('Y-m-').$i.' 17:00:00');
        if( $date->format('D') == 'Sun' )
        {
            $count++;
        }
        if( $count == 2 )
        {
            break;
        }
    }
    $count = 0;
    if( date('Y-m-d H:i:s') > $date->format('Y-m-d H:i:s') )
    {
        for( $i = 1 ; $i <=30 ; $i++ )
        {
            $date = date_create_from_format('Y-m-d H:i:s',date('Y-').(string)(((int)date('n')+1)%12).'-'.$i.' 17:00:00');
            if( $date->format('D') == 'Sun' )
            {
                $count++;
            }
            if( $count == 2 )
            {
                break;
            }
        }
        echo $date->format('F jS, Y');
    }
    else
    {
        echo $date->format('F jS, Y');
    }
?>

So if you are at the green star it will display August 14, and if you're at the blue star it will display September 11:

enter image description here

My question is will this always be correct indefinitely?

  • 写回答

2条回答 默认 最新

  • dreamer1231 2016-04-13 23:43
    关注

    Using DateTime class:

    $date = new DateTime( 'second sunday of this month, 17:00' );
    if( date_create()->diff( $date )->invert )
    {
        $date = new DateTime( 'second sunday of next month, 17:00' );
    }
    

    To retrieve second sunday of this month... just pass “second sunday of this month” to DateTime, then, if the date is in the past (DateInterval->invert return 1 if the interval is negative, 0 otherwise), you can retrieve second sunday of next month.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序