2011-01-13 55 views
1

我只希望只寫出(Y)年份,如果只有它不是從當前年份開始。PHP:如果不是當前年份,寫出年份,時間戳

function get_day_name($timestamp) { 
    $date = date('j-m-Y', $timestamp); 
    if($date == date('j-m-Y')) { 
     $day_name = 'Today'; 
     echo 'idag '; 
    } else if($date == date('j-m-Y',time() - (24 * 60 * 60))) { 
     $day_name = 'Yesterday'; 
     echo 'igår '; 
    }else{ 
    # How can i check here whether the $timestamp is from this year or last year? 
    # If it is from this year then it shouldnt write out the "Y" in $date 
    echo $date; 
    } 
} 

回答

2

根據您原來的職位

# How can i check here whether the $timestamp is from this year or last year? 

我還以爲你是問你怎麼能檢查是否時間戳年是從今年或去年的註釋。所以,我想你的意思是你想知道,例如,如果年份是2011年或2010年。你真正想知道的是時間戳年份是從今年還是任何其他年份,不論是2010年,2009年等。

這是我的第一個答案,根據我的誤會......

$current_year = date('Y'); 
$timestamp_year = date('Y', $timestamp); 
if ($timestamp_year == $current_year || $timestamp_year == $current_year - 1) 

這是你會怎麼想這樣做:

if (date('Y') == date('Y', $timestamp)) 
+0

`日期( 'Y',時間())`和`日期( 'Y')` – Ish 2011-01-13 20:30:04

0

你可以減去$時間戳一年當年(反之亦然)。如果他們不同,結果將是非零的,解決爲真;如果它們是相同的,結果將爲零,解決爲假。

if (date('Y') - date('Y', $timestamp)) { 
    echo date('j F Y', $timestamp); 
} else { 
    echo date('j F', $timestamp); 
} 
相關問題