题
我试图让从我指定之日起一年的日期。
我的代码看起来是这样的:
$futureDate=date('Y-m-d', strtotime('+one year', $startDate));
它返回错误的日期。任何想法,为什么?
解决方案
至一年添加到今天的日期使用下面的:
$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"));
其他提示
$futureDate=date('Y-m-d', strtotime('+1 year'));
$ futureDate为一年,从现在开始!
$futureDate=date('Y-m-d', strtotime('+1 year', strtotime($startDate)) );
$ futureDate为一年,自$的startDate!
尝试:$futureDate=date('Y-m-d',strtotime('+1 year',$startDate));
// 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;
只是有同样的问题,然而,这是最简单的解决方案:
<?php (date('Y')+1).date('-m-d'); ?>
我更喜欢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');
//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'));
希望这个简单的代码位可以帮助别人的未来:)
如果你正在使用PHP 5.3,那是因为你需要设置默认时区:
date_default_timezone_set()
strtotime()
正在返回bool(false)
,因为它不能分析该字符串'+one year'
(它不理解的“1”)。 false
然后被隐式转换为integer
时间戳0
。这是一个好主意来验证你走在其他功能上推搡前strtotime()
的输出不bool(false)
。
返回值
成功返回的时间戳,FALSE 除此以外。上一页到PHP 5.1.0,这 函数将返回-1失败。
尝试这个
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)), date("d",strtotime($startDate)), date("Y",strtotime($startDate))+1));
还有一个更简单和更复杂的解决方案:
$monthDay = date('m/d');
$year = date('Y')+1;
$oneYearFuture = "".$monthDay."/".$year."";
echo"The date one year in the future is: ".$oneYearFuture."";
在我的情况下(我想3年添加到当前日期)的溶液是:
$future_date = date('Y-m-d', strtotime("now + 3 years"));
要Gardenee,Treby和Daniel利马: 将与2月29日发生了什么?有时二月只有28天:)
不隶属于 StackOverflow