6

シンプルな電子メール クライアントを作成しており、受信トレイに電子メールを受信した日付を次の形式で表示する必要があります。

今日の 13:17

昨日 20:38

1 月 13 日 17:15

2012年12月21日 18:12

私はデータベースからデータを取得し、それをxmlに出力して(すべてAJAXを介して実行できるように)、結果を<ul><li>フォーマットに出力しています。

日付と時刻は、次の形式で個別に保存されます。

Date(y-m-d)

Time(H:i:s)

私がこれまでに持っているもの

そのようなことがphpで可能であることがわかりました。ここ - PHP: 日付「昨日」、「今日」

これはJavaScriptを使用して可能ですか?

4

3 に答える 3

3

私はこのようなことで行きます

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);
于 2013-01-15T14:23:54.320 に答える
1

これは、これら2つの回答をまとめたものです(そして、素晴らしいスタートを切るはずです):

何が起こっているのかをよりよく理解するために、質問と回答の両方を読むことをお勧めします。


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
于 2013-01-15T13:57:26.883 に答える
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 の回答です。

于 2013-01-15T15:36:48.753 に答える