PHP日期获取每个期间的开始日期和结束日期

时间:2016-02-16 15:04:14

标签: php date

好的,我试图从一个日期开始计费结束;我的问题是,如果我有一个变量$billing_period = 02/28/2016,并且结算周期是每个月的14th28th。从这个变量中,如何根据开始日期生成具有不同日期的时间段的结束日期?

让我感到困惑的是,如果日期为28th,则1516天除了14th之外,这是一个开始下一个结算周期。如果日期为14th,那么距离28th还有14天。谢谢你的帮助

修改 - 此处的图片显示所选日期02/14/2016如何回显下一个结算日期,该日期仅为开始日期02/28/2016

这是我的数组代码并获取开始日期。

<?
    $date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28','16-04-14','16-04-28',
'16-05-14','16-05-28','16-06-14','16-06-28','16-07-14','16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
'16-11-14','16-11-28','16-12-14','16-12-28');
    $currentdate = date('y-m-d');
 foreach ($date as $i => $d) {
    if ($currentdate >= $d && ($i == count($date)-1 || $currentdate < $date[$i+1])) {
        $selected = "selected";
        $selected_int = $i;
    } else {
        $selected = "";
    }
    list($year, $month, $day) = explode('-', $d);
    echo "<option $selected>" . date("m/d/Y", strtotime($d)) . "</option>";
 }
    ?>

3 个答案:

答案 0 :(得分:1)

希望我理解得很好。

您要做的是根据您之前选择的日期确定哪个是结算周期。

所以,你选择一个日期($ date)。

然后你需要知道所选的一天

$timestamp = strtotime($date);
$day = date('D', $timestamp);

现在你有了你的一天,你可以进行比较。

$datetime = new DateTime($date);
if ($day == 14 ){ // if you select 14th then your billing is on the 28th 
    $billing = $datetime->modify($date->format('Y-m-28'));
}else{ // if you didn't select 14th, then you select 28, and you add one month and set the day in 14th.
    $next_month = $datetime->modify('+1 month');
    $billing = $next_month->modify($date->format('Y-m-14'));
}

答案 1 :(得分:0)

使用开票日期构建一个数组,获取当前密钥并将其递增以获得下一个值。字符串的简单示例:

$dates    = ['02/28/2016', '03/14/2016', '03/28/2016', ...];
$key      = array_search( '03/14/2016', $dates );
$nextDate = $dates[$key + 1]; // 03/28/2016

这是你想要的吗?

答案 2 :(得分:0)

这里的代码可以帮助您了解下一个日期,以防万一您想要一次性完成。

$date = new DateTime();

$next = $date->format('14/m/Y');
if ($date->format('d') >= 14 && $date->format('d') < 28) {
    $next = $date->format('28/m/Y');
}

if ($date->format('d') >= 28) {
    $date->modify('+1 month');
    $next = $date->format('14/m/Y');
}

echo $next;

这里的代码变成了你可以随时调用的函数,它会返回一个DateTime()对象,这样你就可以输出你当时需要的任何格式的日期,或者进行进一步的比较/如果您需要修改,我们需要修改。

function nextBillingDate($date, $format = 'd/m/Y') {
    $date = DateTime::createFromFormat($format, $date);
    $next = $date->format('14/m/Y');
    if ($date->format('d') >= 14 && $date->format('d') <= 28) {
        $next = $date->format('28/m/Y');
    }

    if ($date->format('d') >= 28) {
        $date->modify('+1 month');
        $next = $date->format('14/m/Y');
    }

    return DateTime::createFromFormat('d/m/Y', $next);
}

使用示例:

$date = nextBillingDate('28/02/2016');
echo $date->format('d/m/Y');

输出:

  

14/03/2016

希望它有所帮助。