我正在制作一个包含来自 ajax 调用的数据的表格,并且要求我在每次刷新后显示日期。
我想制作一个计数器来显示上次刷新后经过了多少秒或分钟,但我似乎无法做到这一点。到目前为止我所拥有的是这个,但这只计算秒,如果我想在几分钟内显示,我必须做更多检查
var timestamp = 0;
function updateTime() {
$('#refreshDate').html(timestamp + "seconds ago");
timestamp++;
}
$(function () {
setInterval(updateTime, 1000);
});
结果应该类似于帖子上的 stackoverflow,就像它显示帖子在 x 秒或几分钟前创建的时间
最佳答案
<!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>
关于javascript - 显示自上次 ajax 调用以来的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56121126/