2010-01-02 197 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'));