自上次ajax通话以来的显示时间

时间:2019-05-13 23:35:03

标签: javascript

我正在使用来自ajax调用的数据来做一个表,并且要求每次刷新后显示日期。

我想到做一个计数器来显示上次刷新后经过了几秒钟或几分钟,但是我似乎无法做到这一点。到目前为止,我所拥有的是这个,但这只需要几秒钟,如果我想在几分钟内显示,我必须做更多的检查

    var timestamp = 0;
        function updateTime() {
            $('#refreshDate').html(timestamp + "seconds ago");
            timestamp++;
        }
        $(function () {
            setInterval(updateTime, 1000);
        });

结果应该类似于帖子上的stackoverflow,就像它显示在几秒钟前或几分钟创建帖子的时间一样

3 个答案:

答案 0 :(得分:1)

这应该可以使用长达

var timestamp = 0;
function updateTime() {
  let timeStampDescription = "";
  // year
  if(timestamp > 31536000){
    timeStampDescription = Math.floor(timestamp/31536000) + " years ago"
  // Days
  } else if(timestamp > 86400){
    timeStampDescription = Math.floor(timestamp/86400) + " days ago"
  // Hours
  } else if(timestamp > 3600){
    timeStampDescription = Math.floor(timestamp/3600) + " hours ago"
  // Minutes
  } else if(timestamp > 60) {
    timeStampDescription = Math.floor(timestamp/60) + " minutes ago"
  // Seconds
  } else{ 
    timeStampDescription = timestamp + " seconds ago"
  }
    $('#refreshDate').html(timeStampDescription);
    timestamp++;
}
$(function () {
  setInterval(updateTime, 1000);
});

答案 1 :(得分:1)

您甚至可以使用moment

计算从现在开始的时间
      var myDate = new Date();
      var lastRefresh = document.getElementById("lastRefresh");
      function updateTime() {                              
          lastRefresh.innerText = moment(myDate).fromNow(); // which returns something like: "2 seconds ago"
      }

      setInterval(updateTime, 1000);

答案 2 :(得分:1)

<!DOCTYPE html>
<html>
<body>
 <p id="lastRefresh">Wait.....</p>

<script>
    function setTime(){
       var date = new Date();
       timestamp = date.getTime();
    }

    //Call setTime when you make initial call
    setTime();

    //Set the delay here in ms 
    var updateDelay = 15000;

    var lastRefresh = document.getElementById("lastRefresh");      

    function updateLastRefreshTime() {        
      var currentDate = new Date();
      var currentTime = currentDate.getTime();
      var timeSince = Math.floor((currentTime - timestamp)/1000);
      let timeStampDescription = "";        

      // year
      if(timeSince > 31536000){;
        timeStampDescription = Math.floor(timeSince/31536000) + " years ago"
      // Days
      } else if(timeSince > 86400){
        timeStampDescription = Math.floor(timeSince/86400) + " days ago"
      // Hours
      } else if(timeSince > 3600){
        timeStampDescription = Math.floor(timeSince/3600) + " hours ago"
      // Minutes
      } else if(timeSince > 60) {
        timeStampDescription = Math.floor(timeSince/60) + " minutes ago"
      // Seconds
      } else{ 
        timeStampDescription = timeSince + " seconds ago"
      }
      lastRefresh.innerText = timeStampDescription;          
     }        
     setInterval(updateLastRefreshTime, updateDelay);        

 </script>
 </body>
 </html>