我试图在 6 月 1 日在网页上更新年份(我在这一天需要它,因为它在我生日时更新年份)。问题是:有没有更好的方法用 Vanilla JS 来做到这一点,因为这样我每 24 小时发出一个请求,看看它是否是预期的日期。
document.addEventListener("DOMContentLoaded", function () {
const informationYear = document.getElementById('information-heading-text-year');
// update year function (check every day if its 1st of June and updates the year if true)
function updateYear() {
const birthdayDate = new Date(2013, 5, 1);
let currDate = new Date();
let years = 0;
if(currDate.getMonth() === birthdayDate.getMonth() && currDate.getDay() == birthdayDate.getDay()) {
years = currDate.getFullYear() - birthdayDate.getFullYear();
informationYear.textContent = `${years}+`;
}
}
// 1 day (86,400,000 milliseconds)
const oneDayInterval = 1200;
setInterval(updateYear, oneDayInterval);
});
您认为解决这个问题的最佳方案是什么?是否可以在没有 API 的情况下做到这一点?
我也愿意接受带有数据库和服务器的解决方案
不确定您的确切意思,但假设您想在某些元素中显示给定生日的当前年龄,这可能是一个想法。在代码片段中,生日源自元素上的data 属性。不过,这是否真的更好,由你来判断。
setAge(document.getElementById('information-heading-text-year'));
function setAge(ageElem) {
const [now, birthday] =
[new Date(), new Date(...[ageElem.dataset.birthday.split(`,`)])];
const [yBday, yNow] =
[birthday.getFullYear(), now.getFullYear()];
const birthdayPassed =
new Date(yBday, birthday.getMonth(), birthday.getDate()) > birthday;
const age = yNow - yBday - +(birthdayPassed);
ageElem.textContent = `Current age for ${birthday.toLocaleDateString()} is ${age}`;
}
<h2 id="information-heading-text-year" data-birthday="2013,5,1"></h2>