Home > front end >  Simple way to display "years of service" in html/javascript
Simple way to display "years of service" in html/javascript

Time:11-08

I am trying to display a number for years of service on a website. Essentially I thought I could put in a start date and current date to have an output of the years in between.

I can gt the current year using the following code but am unsure how to calculate the deference

<script>document.write(2010) (/\d{4}/.exec(Date())[0])</script>

CodePudding user response:

Just subtract 2010 from the current year and concatenate the string:

document.write((/\d{4}/.exec(Date())[0]) - 2010   ' years of service')
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Although an easier way to get the year is to use Date.getFullYear():

document.write(new Date().getFullYear() - 2010   ' years of service')
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use Date functions to extract components of time. To get year you can use something like:

today = new Date();
year = today.getFullYear();

To calculate difference between years (year value is number):

d = year - 2010;

CodePudding user response:

You can get like this

document.write(new Date().getFullYear() - 2010)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

document.write(new Date().getFullYear() - 2010)

  • Related