页面最后更新x时间以前在Javascript中

时间:2016-01-20 11:41:44

标签: javascript html

现在我正在使用livestamp.js和moment.js来显示最近x次更新/刷新的页面。但是如果不使用其他js库,可以在普通的js中实现相同的功能。

enter image description here

1 个答案:

答案 0 :(得分:0)



var date = new Date();
var finaltime = timeSince(date);
setInterval(function(){
  document.getElementsByTagName('span')[0].innerHTML = timeSince(date);
},30000);
document.getElementsByTagName('span')[0].innerHTML = timeSince(date);

function timeSince(date) {
  var seconds = Math.floor((new Date() - date) / 1000);
  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval >= 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

<div> This page is updated <span> </span> ago.</div>
&#13;
&#13;
&#13;