Automatic age/number updater

A bit of a random question. There’s a piece of code you can add to a footer so that it automatically updates to the current year for copyright purposes(e.g.: <script>document.write(new Date().getFullYear())</script>). Is there something similar to update an age each year on the person’s birthday?

The easiest thing would to be to just update it manually each year but just curious if there’s a similar piece of code to the one above that does the same thing. (This is for a friend’s daughter’s babysitting website)

This should help…

2 Likes
<script>
        document.addEventListener('DOMContentLoaded', function () {
            // Define the person's birthdate (YYYY, MM - 1, DD)
            // Note: JavaScript months are 0-indexed (0 = January, 11 = December)
            const birthdate = new Date(YYYY, MM - 1, DD);
            const today = new Date();
            let age = today.getFullYear() - birthdate.getFullYear();
            const m = today.getMonth() - birthdate.getMonth();

            // Check if the current date is before the birthday of the current year
            if (m < 0 || (m === 0 && today.getDate() < birthdate.getDate())) {
                age--;
            }

            // Update the age on the webpage
            document.getElementById('age').textContent = age;
        });
    </script>

Replace YYYY, MM, and DD with the birth year, month, and day of the person, respectively. Remember to subtract 1 from the month number since JavaScript counts months from 0 to 11.
The age calculation takes the difference in years between the current year and the birth year. Then, it adjusts this age down by one if the current date is before the birthday in the current year.
The calculated age is then displayed in the webpage by setting the textContent of the element with the id age.

This method ensures that the person’s age is accurately and automatically updated each year on their birthday, based on the client’s system clock, without any need for manual adjustments.

4 Likes

Wow, nicely done! Thanks Kent!