日期减去1年?

时间:2010-01-02 01:43:59

标签: php date

我有这种格式的约会:

2009-01-01

如何返回相同的日期,但提前一年?

8 个答案:

答案 0 :(得分:119)

您可以使用strtotime

$date = strtotime('2010-01-01 -1 year');

strtotime函数返回一个unix时间戳,以获取可以使用date的格式化字符串:

echo date('Y-m-d', $date); // echoes '2009-01-01'

答案 1 :(得分:87)

使用strtotime()函数:

  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

答案 2 :(得分:44)

使用DateTime对象...

$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');

或立即使用今天

$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');

答案 3 :(得分:22)

我使用和运作良好的最简单方法

date('Y-m-d', strtotime('-1 year'));

这很完美..希望这也会帮助别人.. :)

答案 4 :(得分:9)

// set your date here
$mydate = "2009-01-01";

/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));

// format and display the computed date
echo date("Y-m-d", $lastyear);

答案 5 :(得分:3)

尽管对此问题有许多可接受的答案,但我没有看到使用sub对象的\Datetime方法的任何示例:https://www.php.net/manual/en/datetime.sub.php

因此,作为参考,您还可以使用\DateInterval来修改\Datetime对象:

$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));

echo $date->format('Y-m-d');

哪个返回:

2008-01-01

有关\DateInterval的更多信息,请参阅文档:https://www.php.net/manual/en/class.dateinterval.php

答案 6 :(得分:2)

在我的网站上,要检查注册人是否18岁,我只使用了以下内容:

$legalAge = date('Y-m-d', strtotime('-18 year'));

之后,仅比较wo日期。

希望它可以帮助某人。

答案 7 :(得分:-2)

您可以使用以下功能从日期中减去1或任何年份。

 function yearstodate($years) {

        $now = date("Y-m-d");
        $now = explode('-', $now);
        $year = $now[0];
        $month   = $now[1];
        $day  = $now[2];
        $converted_year = $year - $years;
        echo $now = $converted_year."-".$month."-".$day;

    }

$number_to_subtract = "1";
echo yearstodate($number_to_subtract);

在上面的示例中,您还可以使用以下

$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));
相关问题