Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get years between two dates,

  1. Extract both dates and years using the getFullYear() method.
  2. subtract them to get a number of years between dates.

It will return your difference in dates in a number of years.

The getFullYear() method returns the year of the specified date according to local time.

Today, I’m going to show How do I get years between two dates in javascript, here I will use the javascript getFullYear() method and the above-mentioned conditions to get years between the start and end date time.

Let’s start the today’s tutorial How do you get years between two dates in javascript?

In the following example, we are going to do

  1. create two dates starting and ending date
  2. create a function that accepts a date and returns diff years
  3. Use a function for multiple date examples

let’s write the code.

function getYears(startingDate, endingDate) {
    return endingDate.getFullYear() - startingDate.getFullYear();
}

// 👇️ 10
console.log(getYears(new Date('2012-01-15'), new Date('2022-03-16')));

// 👇️ 8
console.log(getYears(new Date('2014-01-15'), new Date('2022-06-16')));

// 👇️ 8
console.log(getYears(new Date('2015-01-15'), new Date('2023-03-16')));

In the above program, we have created a custom function getYears() and pass dates to get a mumber of years.

let’s check the output.

javascript, get years between two dates example
javascript, get years between two dates example

I hope it’s help you, All the best 👍.