【问题标题】:how can i run the loop from start date to end date for every 3 months in php我如何在php中每3个月从开始日期到结束日期运行一次循环
【发布时间】:2016-11-14 20:12:24
【问题描述】:

这里我有一些关于 php date 的问题

代码

$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

有什么简单的方法可以达到效果吗?

【问题讨论】:

  • 描述混乱

标签: php mysql date for-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多