这里我有一些关于 php 日期的问题
代码
$calcdateloops = date("Y-m-01", strtotime(date('Y-m-d')." -1 year -6 Month")); //2015-01-01
$enddate = date('Y-m-d');
所以现在我正在尝试的是我需要将它拆分为 quatar,这意味着每 3 个月一次
预期结果
1) 2015-01-01 - 2015-03-30 // first loop
2) 2015-04-01 - 2015-06-30
3) 2015-07-01 - 2015-09-30
.... so on upto the end date
有什么简单的方法可以达到这个效果吗?
最佳答案
类(class) DateTime和 DateInterval是解决问题的强大工具,您不必关心每个月的天数。
// constructor accepts all the formats from strtotime function
$startdate = new DateTime('first day of this month - 18 months');
// without a value it returns current date
$enddate = new DateTime();
// all possible formats for DateInterval are in manual
// but basically you need to start with P indicating period
// and then number of days, months, seconds etc
$interval = new DateInterval('P3M');
do {
// without clone statement it will copy variables by reference
// meaning that all you variables points to the same object
$periodstart = clone $startdate;
$startdate->add($interval);
$periodend = clone $startdate;
// just subtract one day in order to prevent intersection of start
// and end dates from different periods
$periodend->sub(new DateInterval('P1D'));
echo 'start: ', $periodstart->format('Y-m-d'), ', ', 'end: ', $periodend->format('Y-m-d'), '<br>';
} while ($startdate < $enddate);
关于php - 我如何在 php 中每 3 个月运行一次从开始日期到结束日期的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331360/