php 日期减1年?

z4bn682m  于 10个月前  发布在  PHP
关注(0)|答案(8)|浏览(66)

我有一个这样的约会:

2009-01-01

字符串
如何返回相同的日期,但提前1年?

n9vozmp4

n9vozmp41#

您可以使用strtotime

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

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

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

cwxwcias

cwxwcias2#

使用strtotime()函数:

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

字符串

tktrz96b

tktrz96b3#

使用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');

j8ag8udp

j8ag8udp4#

一个最简单的方法,我使用和工作得很好

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

字符串
这工作完美。希望这也能帮助到其他人。:)

piwo6bdm

piwo6bdm5#

在我的网站上,为了检查注册人是否年满18岁,我简单地使用了以下内容:

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

字符串
之后,只比较两个日期。
希望它能帮助某人。

ghhaqwfi

ghhaqwfi6#

// 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);

字符串

kpbwa7wx

kpbwa7wx7#

虽然有很多可以接受的答案来回答这个问题,但我没有看到任何使用\Datetime对象的sub方法的示例: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

r1zk6ea1

r1zk6ea18#

您可以使用以下函数从日期中减去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'));

相关问题