2013-01-15 85 views
3

我創建一個簡單的電子郵件客戶端,我想收件箱顯示的日期是17:15JavaScript來確定日期和輸出無論是「時間」,如果它是今天,「昨天」昨天,與實際日期,如果是以前那麼

今天13:17

昨天20:38

2012年1月13日@十二月18:12

:該電子郵件的格式接收

我從數據庫中檢索數據,將其輸出到XML(所以一切都可以通過AJAX來完成),並打印結果到<ul><li>格式。

日期和時間分別存儲格式爲:

Date(y-m-d)

Time(H:i:s)

what i have so far

我看到類似的東西可能用PHP。這裏 - PHP: date "Yesterday", "Today"

這是可能使用JavaScript?

回答

1

我會去像這樣的東西

function getDisplayDate(year, month, day) { 
    today = new Date(); 
    today.setHours(0); 
    today.setMinutes(0); 
    today.setSeconds(0); 
    today.setMilliseconds(0); 
    compDate = new Date(year,month-1,day); // month - 1 because January == 0 
    diff = today.getTime() - compDate.getTime(); // get the difference between today(at 00:00:00) and the date 
    if (compDate.getTime() == today.getTime()) { 
     return "Today"; 
    } else if (diff <= (24 * 60 * 60 *1000)) { 
     return "Yesterday"; 
    } else { 
     return compDate.toDateString(); // or format it what ever way you want 
    } 
} 

比你應該能夠得到這樣的日期:

getDisplayDate(2013,01,14); 
+0

何我可以改變格式,以便它可以閱讀2012年8月12日星期日? – Mike

1

這是這兩個答案的彙編(和應該給你一個很好的開始):

我建議閱讀這兩個問題和答覆得到更好地瞭解發生了什麼。


function DateDiff(date1, date2) { 
    return dhm(date1.getTime() - date2.getTime()); 
} 

function dhm(t){ 
    var cd = 24 * 60 * 60 * 1000, 
     ch = 60 * 60 * 1000, 
     d = Math.floor(t/cd), 
     h = '0' + Math.floor((t - d * cd)/ch), 
     m = '0' + Math.round((t - d * cd - h * ch)/60000); 
    return [d, h.substr(-2), m.substr(-2)].join(':'); 
} 

var yesterdaysDate = new Date("01/14/2013"); 
var todaysDate = new Date("01/15/2013"); 

// You'll want to perform your logic on this result 
var diff = DateDiff(yesterdaysDate, todaysDate); // Result: -1.00 
1
function getDisplayDate(year, month, day) { 
    today = new Date(); 
    today.setHours(0); 
    today.setMinutes(0); 
    today.setSeconds(0); 
    today.setMilliseconds(0); 
    compDate = new Date(year,month-1,day); // month - 1 because January == 0 
    diff = today.getTime() - compDate.getTime(); // get the difference between today(at 00:00:00) and the date 
    if (compDate.getTime() == today.getTime()) { 
     return "Today"; 
    } else if (diff <= (24 * 60 * 60 *1000)) { 
     return "Yesterday"; 
    } else { 
     //return compDate.toDateString(); // or format it what ever way you want 
     year = compDate.getFullYear(); 
     month = compDate.getMonth(); 
     months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); 
     day = compDate.getDate(); 
     d = compDate.getDay(); 
     days = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'); 

     var formattedDate = days[d] + " " + day + " " + months[month] + " " + year; 
     return formattedDate; 
    } 
} 

這是@ xblitz與我的格式回答顯示在一個不錯的方式的日期。

相關問題