skip to Main Content

I am trying to make the year on a webpage update on the 1st of June (i need it on this day, because it is updating the year on my birthday). The question is: Is there a better way to do it with Vanilla JS because that way i am making a request every 24 hours to see if it is the expected date.

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);
});

What do you think will be the best solution for this problem? Is it even possible to do it without an API?

I am also open to solutions with database and a server

2

Answers


  1. Chosen as BEST ANSWER

    I was thinking and asked myself, why checking for the exact date each day when i can just calculate the time until that date and set the timeout with that time. So i came up with this solution:

    function updateEmployees() {
        const currentDate = new Date();
        const currentDay = currentDate.getDate();
        const currentMonth = currentDate.getMonth();
        const currentYear = currentDate.getFullYear();
    
        if(currentDate.getDay === 1) {
            informationEmployees.textContent = Number(informationEmployees.textContent) + 1;
        }
    
        if (currentDate.getDay === 15 && (currentDate.getMonth % 2 === 0)) {
            informationEmployees.textContent = Number(informationEmployees.textContent) - 1;
        }
    
        const nextUpdate = new Date(currentYear, currentMonth, 1);
        if (currentDay === 1) {
            nextUpdate.setDate(15);
        } else if (currentDay >= 15) {
            if (currentMonth === 11) { // If it's December, wrap to January of the next year
                nextUpdate.setFullYear(currentYear + 1);
                nextUpdate.setMonth(0); 
            } else {
                nextUpdate.setMonth(currentMonth + 1);
            }
        }
    
        const timeUntilUpdate = nextUpdate - currentDate;
        
        if (timeUntilUpdate > 0) {
            setTimeout(updateEmployees, timeUntilUpdate);
        }
    }
    

    I will definitely try to play with the solution with data attribute you suggested tho.


  2. Not sure what you exactly mean, but assuming you want to display the current age given a birthday in some element, this may be an idea. In the snippet the birthday is derived from a data attribute on the element. It’s up to you to judge if this is actually better though.

    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 birth date ${
        birthday.toLocaleDateString()} is ${age}`;
    }
    <h2 id="information-heading-text-year" data-birthday="2013,5,1"></h2>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search