PHP - 如何计算一个月或一年后

时间:2016-12-06 11:27:40

标签: php date recurly

我想用PHP计算Recurly计划的下一个结算日期。 有两种类型的结算周期:每年|每月。 我尝试使用DateTime和DateInterval类,但没有得到预期的结果。

<?php
$referenceTime = new \DateTime('2016-01-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-03-02 00:00:00.000000'

在Januray的31日增加一个月给了我三月的第二个,而不是我期望的二月的第29个(或第28个)。

8月31日也是如此:

<?php
$referenceTime = new \DateTime('2016-08-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-10-01 00:00:00.000000'

如果每年一次,我预计2016年2月29日+ 1年=&gt; 2017年2月28日

感谢。

5 个答案:

答案 0 :(得分:2)

如果date > 28 use last day of next month使用+1 month

,请尝试此操作
$get_date = strtotime("31-01-2016");
$dt = explode("-",$get_date);
$dt = $dt[0];
var_dump(($dt > 28) ? date("d-m-Y", strtotime("31-01-2016 last day of next month")) : date("d-m-Y", strtotime("31-01-2016 +1 month")));

<强> DEMO

答案 1 :(得分:1)

您可以使用PHP的modify对象调用DateTime来计算相对于当前日期的下一个日期。以下代码显示了如何根据您的具体情况执行此操作。

$next_bill_date = new DateTime();
switch($plan_interval_unit) {
    case "year":
        $next_bill_date->modify("last day of next month");
        break;

    case "month":
        $next_bill_date->modify("last day of this month next year");
        break;
}

答案 2 :(得分:0)

可能是这样的:

if (date('d') !== date('d', strtotime('+1 month'))
    date ('Y-m-d H:i:s', strtotime('last day of next month'));

if (date('d') !== date('d', strtotime('+1 year'))
    date ('Y-m-d H:i:s', strtotime('last day of this month next year'));

答案 3 :(得分:0)

您可以使用PHP内置strtotime()功能

// One month from today
$date = date('Y-m-d', strtotime('+1 month'));

// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2016-12-06')));

答案 4 :(得分:0)

function get_next_billing_date($now, $type, $format = 'Y-m-d')
{
    $date = new DateTime($now);

    $y = $date->format("Y");
    $m = $date->format("m");
    $d = $date->format("d");

    if ($type == 'year') {
        $y++;
        if ($m == 2 && $d == 29) {
            $d = 28;
        }
    } else if ($type == 'month') {
        if ($m == 12) {
            $y++;
            $m = 1;
        } else {
            $m++;
        }

        $first_date = sprintf("%04d-%02d-01", $y, $m);
        $last_day_of_next_month = date('t', strtotime($first_date));

        if ($d > $last_day_of_next_month) {
            $d = $last_day_of_next_month;
        }
    } else {
        // not supported
        return false;
    }

    $date->setDate($y, $m, $d);

    return $date->format($format);
}