gpt4 book ai didi

javascript - 从一个日期算到今天

转载 作者:行者123 更新时间:2023-11-29 20:08:14 26 4
gpt4 key购买 nike

我在这里查看了统计页面:http://movies.io/i/stats

我注意到下面有一个很酷的东西,那里有一个计数器,可以计算网站诞生后的时间和今天的时间。它显示如下:It was born 1 month, 8 days, 2 hours, 36 minutes ago. 我试图在页面上找到代码,但没有成功。

问题是,在搜索操作方法时,我只找到了以天为单位的计数。还有一个问题是刷新它......而不刷新页面。这似乎是一些严肃的编码。

如何在显示的页面上制作一个计数器?我不想使用 jQuery。

如果这听起来像一个问题,我很抱歉:嘿......在我放松的时候做我的工作。但问题是我是新手,我找不到我想做的东西的解决方案。

最佳答案

以无聊的名义...这个页面应该在没有 jquery 的情况下更新 javascript 中的时间跨度。

<!doctype html>
<html>
<body onload="init()">
<script type="text/javascript">
function init() {
updateTimespan();
setInterval(updateTimespan, 3000);
}

function updateTimespan() {
var birth = new Date(1987, 3, 20); // april 20th
var now = new Date();
var timespan = getTimespan(birth, now);

var content = '' + timespan.years + ' years, ' +
timespan.months + ' months, ' +
timespan.days + ' days, ' +
timespan.hours + ' hours, ' +
timespan.minutes + ' minutes, ' +
timespan.seconds + ' seconds.';

var p = document.getElementById('pTimespan');
p.innerHTML = content;
}

function getTimespan(start, end) {
var seconds = end.getSeconds() - start.getSeconds();
var minutes = end.getMinutes() - start.getMinutes();
var hours = end.getHours() - start.getHours();
var days = end.getDate() - start.getDate();
var months = end.getMonth() - start.getMonth();
var years = end.getFullYear() - start.getFullYear();

if (seconds < 0) {
minutes -= 1;
seconds += 60;
}

if (minutes < 0) {
hours -= 1;
minutes += 60;
}

if (hours < 0) {
days -= 1;
hours += 24;
}

if (days < 0) {
months -= 1;
var lastMonthNumber = end.getMonth() - 1;
if (lastMonthNumber < 0) { lastMonthNumber += 12; } // will never be Feb.
var daysInLastMonth = new Date(end.getFullYear(), lastMonthNumber, 0).getDate();
days += daysInLastMonth;
}

if (months < 0) {
years -= 1;
months += 12;
}

return {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds
};
}
</script>
<p>
Time since my birth</p>
<p id="pTimespan">
Will be updated</p>
</body>
</html>

关于javascript - 从一个日期算到今天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11217779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com