php 当前日期 + 2 个月
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10586615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Current date + 2 months
提问by morgi
I wrote this piece of code in order to display the current date + 2 months :
我写了这段代码是为了显示当前日期+ 2个月:
<?php
$date = date("d/m/Y");
$date = strtotime(date("d/m/Y", strtotime($date)) . "+2 months");
$date = date("d/m/Y",$date);
echo $date;
?>
It does not seem to work as it displays : 01/03/1970.
它似乎不起作用,因为它显示:01/03/1970。
What am I doing wrong?
我究竟做错了什么?
Thanks for your help.
谢谢你的帮助。
EDIT :
编辑 :
After reading comments and answers, I simplified and corrected it.
阅读评论和答案后,我对其进行了简化和更正。
<?php
$date = date("d/m/Y", strtotime(" +2 months"));
echo $date;
?>
回答by Alix Axel
You're missing the second argument for the second strtotime()call:
您缺少第二个strtotime()调用的第二个参数:
echo date('d/m/Y', strtotime('+2 months'));
回答by John Conde
Try using the DateTime object:
尝试使用DateTime 对象:
$date = new DateTime("+2 months");
echo $date->format("d/m/Y");
回答by Fenix Lam
If today is "YYYY-mm-31" and next month does not have the 31th day, it will show the next month of that day, make the system display "+3 months" result instead of "+2 months" result.
如果今天是“YYYY-mm-31”,而下个月没有第31天,则显示该日的下一个月,使系统显示“+3个月”结果而不是“+2个月”结果。
So I guess this is the most safety:
所以我想这是最安全的:
$end_date=date("Y-m-d",strtotime("+2 month",strtotime(date("Y-m-01",strtotime("now") ) )));
Change the date to the 1st day first.
首先将日期更改为第一天。
回答by Alph.Dev
Using DateTime->add()or DateTime->modify()
使用DateTime->add()或DateTime->modify()
If you are working with an existing DateTime object, you can use one of these:
如果您正在使用现有的 DateTime 对象,则可以使用以下其中一种:
// Your date
$date = new DateTime(); // empty for now or pass any date string as param
// Adding
$date->add(new DateInterval('P2M')); // where P2M means "plus 2 months"
// or even easier
$date->modify('+2 months');
// Checking
echo $date->format('Y-m-d');
Bewareof adding months in PHP, it may overflow to the next month if the day in the original date is higher than the total number of days in the new month. Same overflow happens with leap years when adding years. Somehow this is not considered a bug by PHP developers and is just documented without a solution. More here: PHP DateTime::modify adding and subtracting months
注意PHP中添加月份,如果原日期的天数大于新月份的总天数,可能会溢出到下个月。添加年份时,闰年也会发生同样的溢出。不知何故,这不被 PHP 开发人员视为错误,只是在没有解决方案的情况下进行了记录。更多信息: PHP DateTime::modify 加减月份
I found this to be the most to-the-point solution to address overflow problem:
我发现这是解决溢出问题的最直接的解决方案:
$day = $date->format('j');
$date->modify('first day of +2 months')->modify('+'. (min($day, $date->format('t')) - 1) .' days');

