【问题标题】:How to get first, third and fifth Saturday of a month in PHP?如何在 PHP 中获取一个月的第一个、第三个和第五个星期六?
【发布时间】:2015-08-03 06:16:30
【问题描述】:

我已经找到了解决这个问题的方法,但是在某些情况下它会出错。以下是我的发现:

此代码段用于打印 2015 年 8 月和 2015 年 7 月的第一个星期六:

$sat = date("F Y",strtotime("2015-08-01"));
echo $fir_sat = "$sat first saturday";
echo " is ".date('d', strtotime($fir_sat));

$sat = date("F Y",strtotime("2015-07-04"));
echo $fir_sat = "$sat first saturday";
echo " is ".date('d', strtotime($fir_sat));

以下是输出:

August 2015 first Saturday is 08
July 2015 first Saturday is 04

但实际上是01

August 2015 first Saturday is 01

它是如何发生的?解决办法是什么?

根据您的反馈,我尝试了一些编码。以下是我的发现。由于php版本而发生的错误。

在 5.2.9 等较低版本的 PHP 中,以下代码不起作用

echo date('Y-m-d', strtotime('2015 年 8 月的第一个星期六'));

但在 5.4 等更高版本中它正在工作

有什么想法吗?

【问题讨论】:

    标签: php date


    【解决方案1】:

    尝试使用of作为

    echo date('d F Y', strtotime('first saturday of $fir_sat'));
    

    “ordinal dayname 'of'”不会提前到另一天。

    而不是

    echo date('d F Y', strtotime('$fir_sat first saturday'));
    

    “ordinal dayname”确实提前到另一天。

    You can check the difference over here

    您也可以查看Docs(Notes)

    【讨论】:

    • 嗨,我认为这不起作用。当我回应这一点时,它指向默认日期,1970 年 1 月 1 日。
    【解决方案2】:

    这样你就可以利用strtotime函数了。

    echo date('d F Y', strtotime('first saturday of August 2015'));
    echo "<br>";
    echo date('d F Y', strtotime('second saturday of August 2015'));
    echo "<br>";
    echo date('d F Y', strtotime('fifth saturday of August 2015'));
    

    确保您在最后传递了正确的年份和月份,因为它会为您提供正确的日期。

    谢谢

    阿米特

    【讨论】:

      【解决方案3】:

      试试这个

      echo date('Y-m-d', strtotime('first saturday of august 2015'));
      echo date('Y-m-d', strtotime('third saturday of august 2015'));
      echo date('Y-m-d', strtotime('fifth saturday of august 2015'));
      

      【讨论】:

        【解决方案4】:

        简单的解决方案,在我的本地测试。

        $sat = date("d F Y",strtotime("2015-08-01"));
        echo $fir_sat = "$sat<br> First saturday";
        echo " is ".date('d', ($fir_sat)); 
        
        
        $thi_sat = strtotime ( '+14 day' , strtotime ( $sat ) ) ;
        $thi_sat = date ( 'd' , $thi_sat );
        echo "<br>third Saturday at ".$thi_sat;
        
        $fifth_sat = strtotime ( '+28 day' , strtotime ( $sat ) ) ;
        $fifth_sat = date ( 'd' , $fifth_sat );
        echo "<br>Fifth Saturday at ".$fifth_sat;
        

        输出是:

        01 August 2015
        First saturday is 01
        third Saturday at 15
        Fifth Saturday at 29 
        

        这可能会有所帮助。干杯!!

        【讨论】:

        • 已更新,根据您的要求生成第一个、第三个和第五个星期六。 :)
        猜你喜欢
        • 2021-12-04
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多