根据数据库值生成日期范围

时间:2016-04-03 19:18:01

标签: php for-loop

我需要根据之前的日期生成几个日期。示例:我的日期格式为dd-mm-yyyy 开始日期从数据库和名称获取为$ startDate。

[01-01-2016 - 03-01-2016]
[04-01-2016 - 06-01-2016]
[07-01-2016 - 10-01-2016]

此差距值来自数据库。我需要使用php循环生成这种日期集。

1 个答案:

答案 0 :(得分:0)

类似的东西,取决于您的需求:

<?php
$dates = [ //new php 'short array' syntax, 
//$dates = array( /* old php start */
'01-01-2016'=> '03-01-2016',
'04-01-2016'=> '06-01-2016',
'07-01-2016'=> '10-01-2016'
//); /* old php end */
];
$f = 'd-m-Y'; //date Format
foreach ($dates as $start=>$end){
    $startDate = date_create_from_format($f, $start);
    $prevDate = date_create_from_format($f, $end);
    $gapDate = clone($prevDate); //pay attention to this line, remove it and see what happens
    $gapDate->add(
        new DateInterval('P1M1D') //google://ISO_8601, PHP manual 
    );

    echo "orig:". $startDate->format($f) . " => " . $prevDate->format($f) ."\n";
    echo "gap_:". $prevDate->format($f) . " => " . $gapDate->format($f) ."\n";
}

//no closing tag here