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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?