2013-07-23 119 views
0

我查看了PHP日期手冊,但找不到任何有關它的文檔。我在荷蘭網站http://marktplaats.nl上找到它。如果你看this url你可以看到'Vandaag'這意味着'今天',他們是怎麼做到的?我如何添加'添加今天'或'昨天添加到我從mysql新添加的記錄?

的代碼我現在有:

<?= date ("d M 'y",strtotime($row['aangeboden-sinds'])); ?> 
+0

[This might help](http://stackoverflow.com/questions/3454258/php-date-yesterday-today) –

+0

可以'你比較文章日期和當前日期? –

+2

如果你對某些類似於stackoverflow的東西感興趣的話,還有一個用於jQuery的漂亮的[timeago](http://timeago.yarp.com/)插件。 (這也將時間計算轉移到客戶端,讓服務器在整個頁面進行日期計算,以及自動更新後的更好UI)。 –

回答

0

很好,這是在SQL中完成的,而不是在應用程序代碼中完成的。以下是在PostgreSQL中如何做到這一點。 (查詢似乎在MySQL 5.6而無需修改工作,這讓我感到驚訝一點點。)

create table test (
    test_id integer primary key, 
    created_at timestamp not null default current_timestamp 
); 

insert into test values 
(1, current_timestamp), 
(2, current_timestamp - interval '1' day), 
(3, current_timestamp - interval '10' day); 

使用CASE語句和簡單的日期計算做你想做的幾乎任何東西。

select test_id, 
     case current_date - cast(created_at as date) 
      when 0 then 'Added today' 
      when 1 then 'Added yesterday' 
      else 'Added some time ago' 
     end as when_added 
from test 
order by created_at desc, test_id asc 

TEST_ID WHEN_ADDED 
-- 
1  Added today 
2  Added yesterday 
3  Added some time ago 

當你order by created_at desc,您的數據自然在顯示順序返回(不考慮任何其他列的應用程序可能需要),並在PHP,你只需要顯示「when_added」一欄。你不需要在php中進行任何操作。

0

這可能只是在UI邏輯簡單的條件。該數據庫本身只是存儲了事情發生的日期,然後在顯示的邏輯,他們可能有一些像(僞代碼):

if (currentDate - storedDate < 1) 
    echo "Today"; 
else if (currentDate - storedDate < 2) 
    echo "Yesterday"; 
else 
    echo storedDate; 

您可以添加一些額外的邏輯來解釋在午夜側翻(用於一個特定的時區,除非你有用戶的時區信息來個性化數學運算)而不是24小時的直接比較,但最終它仍然只是顯示邏輯中的一個條件,而不是關於數據被存儲。

+0

看我的編輯,我已經添加了我目前擁有的代碼,因爲我不知道如何使用它。 –

+0

@KeesSonnema:問題中的代碼應該成功顯示存儲的日期,這將是我的僞代碼中的最後一個條件。對於以前的條件,您需要將其與當前日期進行比較。您可以在PHP中使用兩個日期之間的差異:http://php.net/manual/en/datetime.diff.php – David

+0

不起作用。它給出了'消息:使用未定義的常量storedDate - 假設'storedDate'' –