YEAR DIFFERENCES IN
HTML and Java Script
Calculate Years Before Now
Put a literal age, or "years ago" in your web page and never have to update it

Screenshot of HTML years ago calculation
×
Screenshot of HTML years ago calculation
Why would you want to use it?

You have a birth year, or the year of any event, you want to put something like "Around 70 years ago..." in your text. Each year it is going to need to be updated. The HTML code shown and a short (tiny, tiny wee) script avoid the need for annual attention.

There are two components to this solution. First, in the web page, text like the following marks the place for the year difference:

          
<p>Around <span class="yearsthingy" title="1951"></span> years ago my Grandpop...<p>
          
        

The following script is also required:

          
<script>
  function numberofyears() {
    // Calculates how many years ago a year date (e.g. 1951) is from now
    // Prevents having to update a site for all of the "About 20 years ago..." texts
    // Add a span like this: <span class="yearsthingy" title="1950"></span> 
    // in the flow of the text where class="yearsthingy" and the title is 
    // the date to count from.
    var d = new Date();
    var i, oldyear, y;
    var x = document.getElementsByClassName("yearsthingy");
      for (i = 0; i < x.length; i++) {
        oldyear = parseInt(x[i].title);  
        y = d.getFullYear() - oldyear;
        x[i].innerHTML = y;
      }
  }

  numberofyears()

</script>
          
        

How Does It Work

The span tags with the "yearsthingy" class and the four digit year date in the "title" set a place marker for the point where the years ago will appear in the text. The script looks for all occurrences of the yearsthingy class in tags and for each one calculates the years ago from now, Date(). "x[i].innerHTML = y" writes the years ago value between the "><" symbols between the span tag pairs.

The tags can be used as often as you want in the page, and can all have different year values. Because the "title" is used for the year if the user "mouseovers" the tags the year will be visible as a tooltip (see the example picture above) — quaint!.

Currently, the function doesn't take into account the current month — there you go a little homework, mail me when you have an answer!!

Have fun!