php - 我如何在 php 中每 3 个月运行一次从开始日期到结束日期的循环

标签 php mysql date for-loop

这里我有一些关于 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) DateTimeDateInterval是解决问题的强大工具,您不必关心每个月的天数。

// 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/

相关文章:

mysql - SQL 在 1 个表中选择 2 个条目

iOS日期格式转换

ios - 从复杂的NSString中提取日期

php - 为什么 SoapClient 在文档/文字样式中使用 WSDL 返回带有额外键元素的数组?

javascript - JavaScript 中的表单提交按钮

php - 无法在数据库中插入必填字段

javascript - 使用 jquery 将 mysql 数据获取到新表行

php - 将字符串日期 "Thursday 19th April 2012"转换为日期时间进行操作

php - 从按钮单击 laravel 调用路由

php - 单击时执行 mysql DELETE 查询