I want to create an automatic age updater within a sentence

So basically what I’m looking to do is this… I have my age on my About Me page on my website…

“I’m a 25-year-old part-time blogger & designer and full-time waitress & bartender!”

What I want is for that “25” to automatically change every year on my birthday. I’m terrible at remembering to update it each year.

I really suck at javascript and anything of the sort so I’ll probably need a decent bit of help, full code, or an intense breakdown so I can understand it.

I’m currently using this code to change the year automatically on my copyright page… I’m sure the codes would be similar I just can’t figure it out.

<script type="text/javascript">
var today = new Date()
var year = today.getFullYear()
document.write(year)
</script>

You’re right that the code will be similar.
Years are always a bit tricky, because of how leap years work.

Take a look at this page on creating date objects.
Then take a look at this page on what you can get from a date object.
Then consider this word-form explanation of the answer, and then give it a try yourself:

The number of years between two dates is equal to the difference in year numbers; if the current month is less than the target month, subtract 1. Else, if the months are equal, and the current day is less than the target day, subtract 1.

EDIT: Missed a little bit there. the elseif can only trigger if the months are the same.

1 Like

Thanks, I’ll give it my best shot!

Follow up question! All of what I’ve read makes sense except for how to just display the AGE. Would it be a difference in years?

Yup. Your age is the difference in years between your birthdate and today.

I can get it to display my full birthday but I’m struggling trying to figure out how to make it show a difference in dates. I told you I was not good at any of this lol

Show us your code, and we can help you fix it :wink:

Hi there thatwildhippie,

and a warm welcome to these forums. :winky:

Personally, i would do this server-side with PHP.

If that is an option that you might like to pursue, here is the code…

<?php
/* date in mm/dd/yyyy format */
   $birthDate = '6/17/1993';

/* explode the date to get month, day and year */
   $birthDate = explode( '/', $birthDate );

/* get age from date or birthdate */
    $age = ( 
            date('md', date('U', 
            mktime( 0, 0, 0, 
            $birthDate[0], 
            $birthDate[1], 
            $birthDate[2]))) > date('md') ? 
            ((date('Y') - $birthDate[2]) - 1) : 
            (date('Y') - $birthDate[2])
            );
?>
<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>yearly update</title>

</head>
<body>

 <div> 
  "I’m a<?php echo ' ' . $age; ?>-year-old part-time blogger & designer and full-time waitress & bartender!"
 </div>

</body>
</html>

coothead

This is literally all I have so far, I can’t figure out what else I need to make the difference happen. Clearly I know there’s much more code needed but for the life of me I have no idea…

<!DOCTYPE html>
<html>
<body>

<p id="demo">Display the result here.</p>

<script>
var d = new Date("October 23, 1992 00:00:00");
document.getElementById("demo").innerHTML = d.toDateString();
</script>

</body>
</html>

Yikes. If I were going to do it in php, i’d do

<?php
$bdate = new DateTime("6/17/1993");
$age = $bdate->diff(new DateTime())->y;
?>
1 Like

Well, you’re obviously very much better at PHP than me. :winky:

With that simplicity, It also confirms that PHP is definitely
the better option. :sunglasses:

coothead

okay, so we’ve got one of our Date objects.

var d = new Date("October 23, 1992 00:00:00");

For the sake of sanity, we also have today’s date from elsewhere in the script:

var today = new Date()

We know that we can get the year, as you showed in the OP:

var year = today.getFullYear()

The page on get functions tells you that this returns a 4 digit number.
So, get the year from our birthday object;

var byear = d.getFullYear();

the difference in those values, then is:

var dyear = year - byear;

(Year should always be greater than byear, unless you were born in the future, so we know that this value is positive.)
But, we need to do more, because we dont know about the month and day yet. You should get a different answer if today is in September than you do if it’s November, because you’ve had a birthday.
So, back to the method page, which tells us we can get a month from our objects, and the day too, which we’ll need later.

var month = today.getMonth();
var bmonth = d.getMonth();
var day = today.getDate();
var bday = d.getDate();

We then check to see if the current month is less than the target month: if it is, we subtract 1.

if(month < bmonth) {
  dyear--;
}

but we’re STILL not done, because if it’s the same month, we need to check the day to do a comparrison there, too…

else if(month == bmonth && day < bday) {
 dyear--;
}

At this point, dyear is the numerical value of the number of years between the two dates.

If i was doing this in actual code rather than in explanation form, i wouldnt declare all those vars, and would instead just call the functions in-situ, that is to say I would reduce this:

var d = new Date("October 23, 1992 00:00:00");
var today = new Date();
var year = today.getFullYear();
var byear = d.getFullYear();
var dyear = year - byear;
var month = today.getMonth();
var bmonth = d.getMonth();
var day = today.getDate();
var bday = d.getDate();
if(month < bmonth) {
  dyear--;
}
else if(month == bmonth && day < bday) {
 dyear--;
}

To this:

let d = new Date("October 23, 1992 00:00:00");
let today = new Date();
let dyear = today.getFullYear() - d.getFullYear();
if(today.getMonth() < d.getMonth()) {
  dyear--;
}
else if(today.getMonth() == d.getMonth() && today.getDate() < d.getDate()) {
 dyear--;
}

But yes, this is still a lot longer than doing it in a server language like PHP, as @coothead pointed out.

Hi there thatwildhippie,

according to @m_hutley 's superior skills, the code
that I supplied in post #8* should have been this…

<?php
/* date in mm/dd/yyyy format */
   $bdate = new DateTime( "6/17/1993" );
   $age = $bdate -> diff(new DateTime()) -> y;
?>

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>yearly update</title>

</head>
<body>

 <div> 
  "I’m a<?php echo ' ' . $age; ?>-year-old part-time blogger & designer and full-time waitress & bartender!"
 </div>

</body>
</html>

coothead

Okay so. this made 100% sense & I get how it works… but I can’t get anything to appear. And I think I know why…

I need to change this section so it displays the proper bit but I dont know what to replace it with…

document.getElementById("demo").innerHTML = d.toDateString()

this is what I have… it works but I’m not totally sure if it’s correct.

var d = new Date("October 23, 1992 00:00:00");
let today = new Date();
let dyear = today.getFullYear() - d.getFullYear();
if(today.getMonth() < d.getMonth()) {
  dyear--;
}
else if(today.getMonth() == d.getMonth() && today.getDate() < d.getDate()) {
 dyear--;
}

document.getElementById("demo").innerHTML = d.toDateString()

So… we put the difference into dyear. So… you’d… put dyear into the thing instead of d.toDateString?

1 Like

You’re wonderful!!! Thank you both so much! It works and better yet yall helped me actually understand it vs just doing it or pointing and leaving

3 Likes

One last problem… it works in a js viewer but i can’t get it displayed on my website. im sure im just placing the code in the wrong place

If you’re putting the script at the top of the page, then this line:

document.getElementById("demo").innerHTML = dyear

wont be able to find “demo”, because the element doesn’t exist yet.

Put it at the bottom of the page, or call the line inside of an event listener, listening to the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', function (event) {
   //rest of the code...
}

I was using

<script type="text/javascript" src="age.js"></script>

because I put all of my scripts on their own page instead of embedding them all on my header file so how can I change the code to pull from there?

Same thing - move that line to the bottom of the file. (or anywhere AFTER the point where you’ve put the element with ID “demo”, for that matter)