読者です 読者をやめる 読者になる 読者になる

IT業界のすみっこ暮らし

ふと気がついたときの記録

timestampから経過時間を表示する(Javascript)

// timestampより経過時間を取得
function GetLapsedTime(timestamp) {
    if (timestamp == "" || timestamp == null || timestamp == "0") {
        return "";
    }
    //timestampをdateに変換
    var d = new Date(timestamp * 1000);
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var hour = (d.getHours() < 10) ? '0' + d.getHours() : d.getHours();
    var min = (d.getMinutes() < 10) ? '0' + d.getMinutes() : d.getMinutes();
    var sec = (d.getSeconds() < 10) ? '0' + d.getSeconds() : d.getSeconds();
    var from = new Date(year + "/" + month + "/" + day + " " + hour + ":" + min + ":" + sec);
    //現在時間(サーバ時間)経過時間取得用
    var now = new Date();
    //経過時間(秒)を取得
    var interval = (now - from);
    var msecPerMinute = 1000 * 60;
    var msecPerHour = msecPerMinute * 60;
    var msecPerDay = msecPerHour * 24;

    //経過時間表示文言作成
    var DayPeriod = Math.floor(interval / msecPerDay);
    interval = interval - (DayPeriod * msecPerDay);

    if (DayPeriod < 1) {
        var HourPeriod = Math.floor(interval / msecPerHour);
        interval = interval - (HourPeriod * msecPerHour);

        if (HourPeriod < 1) {
            var MinutePeriod = Math.floor(interval / msecPerMinute);
            interval = interval - (MinutePeriod * msecPerMinute);

            if (MinutePeriod < 1) {
                var SecondPeriod = Math.floor(interval / 1000);
                return SecondPeriod + "秒前";
            }
            else {
                return MinutePeriod + "分前";
            }
        }
        else {
            return HourPeriod + "時間前";
        }
    }
    else if ((DayPeriod > 0) && (DayPeriod < 7)) {
        return DayPeriod + "日前";
    }
    else if (DayPeriod == 7) {
        return "1週間前";
    }
    else {
        // "YYYY年MM月DD日"形式で表示
        return from.getFullYear() + "年" + convertNum((from.getMonth() + 1), 2) + "月" + convertNum(from.getDate(), 2) + "日";
    }
}