2012-06-05 145 views
1

我看過這個論壇,發現了一些關於使用jQuery轉換時間戳的相似帖子。 但我沒有找到一次解決我的問題。如何比較時間戳

我在一個web應用程序,結合JQuery的移動工作。 在這個Web應用程序即時顯示一些Twitter飼料:圖像和消息。現在即時通訊也試圖讓日期在那裏。

Wehn IM從JSON它這樣以便在檢索日期:

Tue, 05 Jun 2012 13:25:06 +0000 

現在我想對這個日期與當前日期來計算時間過去比較。 這是因爲我想說:1秒前,2分鐘前1小時前等

有人可以告訴我,我可以如何比較當前日期與Twitter日期?

回答

1
var twitterDate = new Date("Tue, 05 Jun 2012 13:25:06 +0000").getTime(), 
    now = new Date().getTime(); 

if (twitterDate > now) { 
    alert('Future') 
} else { 
    alert('Past'); 
} 

DEMO

由getTime方法返回的值是自1970年1月1日0時零零分00秒UTC毫秒 數。

閱讀.getTime()

而獲得的時間差,你可以下面的方法:

function getDateDiff(twitterDate, interval) { // interval means unit, 
    // in which you want the result 
    var second = 1000, 
     minute = second * 60, 
     hour = minute * 60, 
     day = hour * 24, 
     week = day * 7; 
    date1 = new Date(twitterDate).getTime(); 
    date2 = new Date().getTime(); 
    var timediff = date2 - date1; 
    if (isNaN(timediff)) return NaN; 
    switch (interval) { 
    case "years": 
     return date2.getFullYear() - date1.getFullYear() + ' years ago.'; 
    case "months": 
     return ((date2.getFullYear() * 12 + date2.getMonth()) - (date1.getFullYear() * 12 + date1.getMonth())) + ' months ago.'; 
    case "weeks": 
     return Math.floor(timediff/week) + ' weeks ago.'; 
    case "days": 
     return Math.floor(timediff/day) + ' days ago.'; 
    case "hours": 
     return Math.floor(timediff/hour) + ' hours ago.'; 
    case "minutes": 
     return Math.floor(timediff/minute) + ' minutes ago.'; 
    case "seconds": 
     return Math.floor(timediff/second) + ' seconds ago.'; 
    default: 
     return undefined; 
    } 
} 

用途:

getDateDiff("Tue, 05 Jun 2012 13:25:06 +0000", "seconds"); 
+0

首先謝謝你,我覺得它幾乎工作,但又有一個問題。當我試圖把它放在案件開關我似乎無法得到它的工作。即時通訊使用大小寫切換來確定過去有多少時間來顯示消息。 1分鐘前等 – pum

+0

@pum檢查我的更新答案和演示 – thecodeparadox

+0

它的工作謝謝你:D – pum

2

您可以在JavaScript中比較時間戳這樣。

var input_date = new Date('Tue, 05 Jun 2012 13:25:06 +0000').getTime(); 
var curr_date = new Date().getTime(); 
if(input_date > curr_date){ 
    alert("greater");  
}else{ 
    alert('small'); 
} 

這裏是Demo

但是按照您的要求,你要顯示的時間,如「1分鐘前」,「1小時前」,「2天前」,您可以使用jquery timeago插件而不是做javascrpt計算。請參閱this plugin,它會滿足您的需求。

+0

+1不要重新制造一些東西,特別是當它已經完成。如果整個插件過度滿足您的需求,請將相關部件從其中剝離出來並整合到您自己的東西中。通常情況下,在開源項目中會出現邊緣案例,否則您可能會錯過這些邊緣案例。 –