2012-03-17 114 views
4

如何使用PHP代碼獲取去年的開始和結束日期?可能嗎?今年我如何獲得去年的開始和結束日期?

+0

你能詳細解釋一下以便得到正確答案嗎? – 2012-03-17 06:24:24

+5

全年從1月1日開始,到12月31日結束,不幸的是! – Sourav 2012-03-17 06:25:01

回答

6

第一天總是1月1日,最後一天始終是12月31日你真的只改變附加的年份。這取決於你如何想的日期格式,你有幾個可能性...

  1. 如果你只是想顯示物理日期:如果您需要的時間戳這兩個

    $year = date('Y') - 1; // Get current year and subtract 1 
    $start = "January 1st, {$year}"; 
    $end = "December 31st, {$year}"; 
    
  2. 日期:

    $year = date('Y') - 1; // Get current year and subtract 1 
    $start = mktime(0, 0, 0, 1, 1, $year); 
    $end = mktime(0, 0, 0, 12, 31, $year); 
    

非常簡單的東西。如果您想要,也可以手動指定哪一年。前提是一樣的。

0

開始日期:今年

mktime(0,0,0,1,1,$year); 

結束日期:

mktime(0,0,0,1,0,$year+1); 
+0

那麼'$ year'在這裏的價值是多少? – Kichu 2012-03-17 06:18:07

+0

並且不認爲此函數已被棄用,只有當您使用它沒有參數時,纔會顯示使用time()函數的E_STRICT通知。使用這個參數的功能還是不錯的。 – 2012-03-17 06:18:18

+0

$年是你想要的年份的價值。如果你想要2012年1月1日和2012年12月31日,年份將是2012年。 – 2012-03-17 06:18:55

0

檢查這個東西

$currentY = date('Y'); 
$lastyearS = mktime(0, 0, 0, 1, 1, $currentY-1)."<br/>"; 
$lastyearE = mktime(0, 0, 0, 12, 31, $currentY-1)."<br/>"; 
echo date('Y-m-d',$lastyearS)."<br/>";echo date('Y-m-d',$lastyearE); 
0

想,如果你當月是月或有30天

echo date('Y-12-t', strtotime(date('Y-m-d'))); // if current month is february (2015-02-01) than it gives 2015-02-28 

會給你不準確的結果

解決方案的一個月:

因此,要獲得一個一年的結束日期準確的結果,請嘗試以下

$start_date = date("Y-01-01", strtotime("-1 year"));// get start date from here 
$end_date = date("Y-12-t", strtotime($start_date)); 

(OR)的代碼

$last_year_last_month_date = date("Y-12-01", strtotime("-1 year")); 
$end_date = date("Y-12-t", strtotime($last_year_last_month_date)); 
1

您可以通過使用下面的做到這一點。希望它能幫助別人。

//to get start date of previous year 
echo date("d-m-y",strtotime("last year January 1st")); 

//to get end date of previous year 
echo date("d-m-y",strtotime("last year December 31st")); 
相關問題