繁体   English   中英

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

[英]PHP Dates getting a start date and end date for each period

好吧,我正在尝试从一个日期算起帐单周期的结束时间; 我的问题是,如果我有一个变量$billing_period = 02/28/2016 ,并且帐单周期在每月的14th28th 从这个变量中,如果它们的开始日期不同,我如何生成时段的结束日期?

令我感到困惑的是,如果日期是28th日,那么它与下一个计费周期开始的14th日之间相隔15天或16天。 如果日期是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>";
 }
    ?>

希望我理解得很好。

您要执行的操作是根据先前选择的日期确定哪个结算周期。

因此,您选择一个日期($ 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'));
}

用帐单日期构建一个数组,获取当前密钥并增加它以获得下一个值。 带字符串的简单示例:

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

这就是你想要的吗?

这里的代码可以让您下次约会,以防万一。

$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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM