X分钟前JavaScript函数不工作
我正在尝试使用以下JavaScript动态更新1分钟前的时间戳X分钟前JavaScript函数不工作,javascript,Javascript,我正在尝试使用以下JavaScript动态更新1分钟前的时间戳 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); }
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:
我得到的错误是:
未捕获引用错误:未定义相对时间
您没有在fiddle上定义jQuery,您的函数用法早于函数声明,并且您的Date
声明使用了错误的格式
function relativeTime() {
$('#time').text(timeSince('2015-09-17T14:59:10'));
}
setInterval(relativeTime, 1000);
查看@Travis的答案也可以获得更好的code
我能问一下你为什么不使用moment.js吗?你说它不工作。。你这是什么意思?是否有错误?请使用浏览器中的开发人员工具Uncaught SyntaxError:missing)参数列表后
@Quentin:Updated this:was缺少引号。仍然不工作。继续使用开发人员工具。您会得到一个新的错误,它告诉您尝试求值的函数不是全局函数。如果您解决了这个问题,那么您将得到另一个新错误,它告诉您尚未加载jQuery。