如何在 PHP 中的月底后添加天数

How can I add a number of days after an end of the month in PHP

我的目标是打印截止日期。 到期日公式是月底加上天数,在我的例子中是 7 天。 我怎样才能让它成为可能? 我对实际结果的回应值是 "Due date: 08/01/1970" 我的预期结果是 "Due date: 07/06/2018"

$invoice_date = "11/05/2018";
$days  = 7;
$is_invoice = false;

$date = date("d/m/Y", strtotime($invoice_date));

if ($is_invoice) {
    $dueDate = date('d/m/Y', strtotime("+$day $days", strtotime($date)));
} else {
    $dueDate = date('t/m/Y', strtotime($date));
    $dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
}

echo "Due date: $dueDate";

在此先感谢您的帮助

我建议您使用 DateTime class 和相关函数:

$invoice_date = "11/05/2018";
$days = 7;

$input = date_create_from_format('d/m/Y', $invoice_date);
$result = $input->add(new DateInterval("P${days}D"));

$dueDate = $result->format('d/m/Y');

echo "Due date: $dueDate";

输出:

Due date: 11/05/2018

尝试使用 DateTime class:

$date = DateTime::createFromFormat('d/m/Y', '11/05/2018');

$dueDate = clone $date;
$dueDate->modify('+7 days');

echo 'Date : ' . $date->format('d/m/Y') . "\n";
echo 'Due  : ' . $dueDate->format('d/m/Y') . "\n";

输出:

Date : 11/05/2018 
Due : 18/05/2018

看这里:https://3v4l.org/BjUSK

除了未定义变量错误外,您的编码逻辑是完美的

$invoice_date = "11/05/2018";
$day  = 7;//in below statements used as day
$is_invoice = false;

$date = date("d/m/Y", strtotime($invoice_date));

if ($is_invoice) {
    $dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
} else {
    $dueDate = date('t/m/Y', strtotime($date));
    $dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
}

echo "Due date: $dueDate";

Undefined variable $day;//将days改为day

月底 + 7 天是我读到的......如果我错了请纠正我:

$invoice_date= '11/05/2018';
$days= 7;

$dueDate= DateTime::createFromFormat('d/m/Y', $invoice_date);
$dueDate->modify('last day of this month')->modify('+7 days');
echo $dueDate->format('d/m/Y');

发票日期 11/5/2018 returns 7/6/2018

$invoice_date = "11-05-2018";
$day  = 7;//in below statements used as day
$is_invoice = false;

$date = date("Y/m/d", strtotime($invoice_date));

if ($is_invoice) {
$dueDate = date('d/m/Y', strtotime($date. ' + '.$day.' days'));
} else {
$dueDate = date('Y-m-t', strtotime($date));
$dueDate = date('d/m/Y', strtotime($dueDate. ' + '.$day.' days'));
}

echo "Due date: ".$dueDate;