PHP 日期 向当前日期添加 5 年

php
2022-08-30 08:19:33

我有这个PHP代码:

$end=date('Y-m-d');

我用它来获取当前日期,并且我需要将来5年的日期,如下所示:

$end=date('(Y + 5)-m-d');

我该怎么做?


答案 1

尝试使用:

$end = date('Y-m-d', strtotime('+5 years'));

答案 2

基于这个帖子
修改日期 strtotime() 非常强大,并且允许您使用它的相对表达式轻松修改/转换日期:

过程

    $dateString = '2011-05-01 09:22:34';
    $t = strtotime($dateString);
    $t2 = strtotime('-3 days', $t);
    echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100

日期时间

    $dateString = '2011-05-01 09:22:34';
    $dt = new DateTime($dateString);
    $dt->modify('-3 days');
    echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100

你可以在 strtotime() 上扔的东西非常令人惊讶,而且非常人性化。看看这个例子,寻找下周的星期二。

程序

    $t = strtotime("Tuesday next week");
    echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100

日期时间

    $dt = new DateTime("Tuesday next week");
    echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100

请注意,上面的这些示例是相对于现在的时间返回的。strtotime() 和 DateTime 构造函数采用的时间格式的完整列表列在 PHP 支持的日期和时间格式页面上

另一个例子,适合你的情况可能是:基于这篇文章

    <?php
    //How to get the day 3 days from now:
    $today = date("j");
    $thisMonth = date("n");
    $thisYear = date("Y");
    echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear)); 

    //1 week from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));

    //4 months from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear)); 

    //3 years, 2 months and 35 days from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
    ?>

推荐