我正在尝试从我指定的日期开始一年的日期。
我的代码如下所示:
$futureDate=date('Y-m-d', strtotime('+one year', $startDate));
它回复了错误的日期。有什么想法吗?
答案 0 :(得分:181)
$futureDate=date('Y-m-d', strtotime('+1 year'));
$ futureDate是从现在开始的一年!
$futureDate=date('Y-m-d', strtotime('+1 year', strtotime($startDate)) );
$ futureDate是$ startDate的一年!
答案 1 :(得分:77)
要在今天的日期添加一年,请使用以下内容:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));
对于其他示例,您必须使用时间戳值初始化$ StartingDate 例如:
$StartingDate = mktime(); // todays date as a timestamp
试试这个
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));
或
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));
答案 2 :(得分:7)
尝试:$futureDate=date('Y-m-d',strtotime('+1 year',$startDate));
答案 3 :(得分:6)
// Declare a variable for this year
$this_year = date("Y");
// Add 1 to the variable
$next_year = $this_year + 1;
$year_after = $this_year + 2;
// Check your code
echo "This year is ";
echo $this_year;
echo "<br />";
echo "Next year is ";
echo $next_year;
echo "<br />";
echo "The year after that is ";
echo $year_after;
答案 4 :(得分:5)
只是遇到了同样的问题,但这是最简单的解决方案:
<?php (date('Y')+1).date('-m-d'); ?>
答案 5 :(得分:3)
//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));
//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));
希望这段简单的代码可以帮助将来的人:)
答案 6 :(得分:2)
如果您使用的是PHP 5.3,那是因为您需要设置默认时区:
date_default_timezone_set()
答案 7 :(得分:2)
strtotime()
正在返回bool(false)
,因为它无法解析字符串'+one year'
(它不理解“一”)。然后,false
被隐式转换为integer
时间戳0
。在将其推送到其他函数之前验证strtotime()
的输出不是bool(false)
是个好主意。
返回值
返回成功时间戳,FALSE 除此以外。在PHP 5.1.0之前,这个 函数在失败时返回-1。
答案 8 :(得分:2)
我更喜欢OO方法:
$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))
使用DateTimeImmutable
否则您也会修改原始日期!
更多关于DateTimeImmutable:http://php.net/manual/en/class.datetimeimmutable.php
如果您只想从今天开始,那么您可以随时执行:
new \DateTimeImmutable('-1 Month');
答案 9 :(得分:1)
试试这个
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)), date("d",strtotime($startDate)), date("Y",strtotime($startDate))+1));
答案 10 :(得分:1)
我的解决方法是:date('Y-m-d', time()-60*60*24*365);
您可以通过定义使其更“可读”:
define('ONE_SECOND', 1);
define('ONE_MINUTE', 60 * ONE_SECOND);
define('ONE_HOUR', 60 * ONE_MINUTE);
define('ONE_DAY', 24 * ONE_HOUR);
define('ONE_YEAR', 365 * ONE_DAY);
date('Y-m-d', time()-ONE_YEAR);
答案 11 :(得分:0)
还有一种更简单,不太复杂的解决方案:
$monthDay = date('m/d');
$year = date('Y')+1;
$oneYearFuture = "".$monthDay."/".$year."";
echo"The date one year in the future is: ".$oneYearFuture."";
答案 12 :(得分:-2)
在我的情况下(我想在当前日期增加3年),解决方案是:
$future_date = date('Y-m-d', strtotime("now + 3 years"));
Gardenee,Treby和Daniel Lima: 2月29日会发生什么?有时二月只有28天:)