添加三个月在PHP的日期

问题描述 投票:66回答:10

我有一个名为$effectiveDate包含日期2012-03-26变量。

我想三个月到这个日期,并已成功吧。

这是我曾尝试:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));

$effectiveDate = strtotime(date("Y-m-d", strtotime($effectiveDate)) . "+3 months");

我究竟做错了什么?无论是一段代码工作。

php date strtotime
10个回答
162
投票

将其更改为这会给你所需的格式:

$effectiveDate = date('Y-m-d', strtotime("+3 months", strtotime($effectiveDate)));

0
投票

以下应该工作

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

5
投票

我认为是“不工作”你的意思是它给你一个时间戳,而不是格式化的日期,因为你做正确:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version

5
投票

这个答案是不完全对这一问题。但我会添加这个,因为这个问题仍然对搜索如何从日期添加/扣除期间。

$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

3
投票

Tchoupi's答案可制成一点点通过连接论据的strtotime()如下更简洁:

$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );

(这依赖于神奇的实现细节,但你可以经常去看看他们,如果你正确地不信任。)


2
投票

您需要将日期转换为可读值。您可以使用的strftime()或日期()。

尝试这个:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;

这应该工作。我喜欢用的strftime更好,因为它可以用于本地化你可能想尝试一下。


2
投票

添加第n天,月,年

$n = 2;
for ($i = 0; $i <= $n; $i++){
    $d = strtotime("$i days");
    $x = strtotime("$i month");
    $y = strtotime("$i year");
    echo "Dates : ".$dates = date('d M Y', "+$d days");
    echo "<br>";
    echo "Months : ".$months = date('M Y', "+$x months");
    echo '<br>';
    echo "Years : ".$years = date('Y', "+$y years");
    echo '<br>';
}

1
投票

以下应工作,请试试这个:

$effectiveDate = strtotime("+1 months", strtotime(date("y-m-d")));
echo $time = date("y/m/d", $effectiveDate);

0
投票

以下应工作,但您可能需要更改格式:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

0
投票

您可以使用从PHP简单图书馆simpleDate类:

include('../code/simpleDate.php');
$date = new simpleDate();
echo $date->set($effectiveDate)->addMonth(3)->get();

检查library tutorials here

© www.soinside.com 2019 - 2024. All rights reserved.