X分钟前JavaScript功能无法正常工作

时间:2015-09-17 17:52:34

标签: javascript

我正在尝试使用以下JavaScript动态更新时间戳1 minute ago

setInterval('relativeTime()', 1000);

function relativeTime()
{
    console.log(timeSince('2015-09-17 14:59:10'));
}


function timeSince(date) {
    if (typeof date !== 'object') {
        date = new Date(date);
    }

    var seconds = Math.floor((new Date() - date) / 1000);
    var intervalType;

    var interval = Math.floor(seconds / 31536000);
    if (interval >= 1) {
        intervalType = 'year';
    } else {
        interval = Math.floor(seconds / 2592000);
        if (interval >= 1) {
            intervalType = 'month';
        } else {
            interval = Math.floor(seconds / 86400);
            if (interval >= 1) {
                intervalType = 'day';
            } else {
                interval = Math.floor(seconds / 3600);
                if (interval >= 1) {
                    intervalType = "hour";
                } else {
                    interval = Math.floor(seconds / 60);
                    if (interval >= 1) {
                        intervalType = "minute";
                    } else {
                        interval = seconds;
                        intervalType = "second";
                    }
                }
            }
        }
    }

    if (interval > 1 || interval === 0) {
        intervalType += 's';
    }

    return interval + ' ' + intervalType;
};

jsFiddle:http://jsfiddle.net/5qpxrta9/2/

我得到的错误:

  

未捕获的ReferenceError:未定义relativeTime

2 个答案:

答案 0 :(得分:1)

你没有在小提琴上定义jQuery,你的函数用法在你的函数声明之前,并且你的Date声明使用了错误的格式。

function relativeTime() {
    $('#time').text(timeSince('2015-09-17T14:59:10'));
}

setInterval(relativeTime, 1000);

答案 1 :(得分:0)

查看@Travis的答案还有更好的code

http://jsfiddle.net/9yh9c7xh/2/