繁体   English   中英

如何在PHP中获得一个月的第一,第三和第五个星期六?

[英]How to get first, third and fifth Saturday of a month in PHP?

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

此代码段将打印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中,以下代码不起作用

回音日期('Ym-d',strtotime('2015年8月的第一个星期六'));

但是在像5.4这样的更高版本中,它正在萎缩

有任何想法吗?

尝试使用of作为

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

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

代替

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

“序数日”确实提前到了另一天。

你可以在这里查看差异

您还可以查看文档(备注)

这样你就可以利用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'));

确保你最后通过适当的年份和月份,因为它会给你正确的日期。

谢谢

阿米特

试试这个

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'));

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

$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 

这可能会有所帮助。欢呼!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM