2010-01-02 247 views
61

我有这种格式的日期:日期减1年?

2009-01-01 

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

+0

不要忘记倾向于你的意思是“一年”什么语义问题w.r.t.闰年。从2008-02-28减去365天会给你2007-02-28,而从2008-02-29减去365天会给你2007-03-31。 – HostileFork 2010-01-02 02:16:23

+0

我想这很大程度上取决于“减去一年”的含义。你可能意思是同一个月和一天,但是在一年前或者在敌对指出的365天后减少的那一天和那一天。 – 2010-01-02 02:33:05

回答

96

您可以使用strtotime

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

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

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

使用的strtotime()函数:

$time = strtotime("-1 year", time()); 
    $date = date("Y-m-d", $time); 
8
// 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); 
31

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

我用它和行之有效

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

这个工作完美的最简单的方法..希望这会帮助别人.. :)

0

你可以使用followi ng函数从日期中减去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')); 
相关问题