Calculate The Difference Between Two (2) dates with JavaScript
Tags: javascript, programming, tutorial, 100daysofcode
Published: 2022-06-03 00:21:00

There are so many things that you could do with a date & time calculator. With a date & time calculator, you can calculate how many days it may take for delivery to arrive, how many months it may take for a subscription to expire, or maybe you want to build your own time calculator like this [Amazing App](https://www.timeanddate.com/), name it …

In this article, I will show you how you can create a simple function that will help to calculate the difference between two dates.

## LET'S BEGIN

I will call the function `calDate()` short for ‘calculateDate’.

This function will have 2 parameters which are date1 and date2 and these 2 dates must be in the format **MM-DD-YYYY** (Month-Day-Year), to avoid errors during calculation.

I love writing dates in the format **DD-MM-YYYY**, but in this article, I happen to not be in support of this guy 😅.

![programming jokes: I find other date formats confusing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nno0i4rvu04qpzjadlb4.png)
 
Now, let's start off with the function.

```javascript
function calcDate(date1, date2){
/*
* calcDate() : Calculates the difference between two dates
* @date1 : "First Date in the format MM-DD-YYYY"
* @date2 : "Second Date in the format MM-DD-YYYY"
* return : Array
*/
}
```
I will create a new instance of a `Date` object and find the **timestamps** of both dates

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */
    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);
}
```
Next, we have to prevent negative values as we subtract a **higher timestamp** from a **lower timestamp** because this can ruin our result.

I will use a condition to check which timestamp is greater and then swap them, as you can see on line 18.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */
    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
}
```
I have passed the result of subtracting timestamp 2 from timestamp 1 as an argument to a new date instance in order for JavaScript to convert the resulting timestamp to date.

Next, we have to retrieve the **days, months, and years** from the result and then join them with a hyphen. This will help us to convert it to an array that we will read from later.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */

    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
}
```
If you observed the code above, you’ll notice that I added **+1** to the `getMonth()` method.

This is because JavaScript counts months from a zero index, this means that **0 — 11** is January up to December, so

- 0 is for January
- 1 is for February
- up to 11 for December.

On line 26, I drafted how the array would look like, with the format **DD-MM-YYYY**, then on line 28, I used the split method to convert the draft to an array.

## IT’S TIME TO READ FROM THE ARRAY

The array was created in this format:

- At position 0 is the Day
- At position 1 is the Month
- At position 2 is the Year

We will subtract each member of this array from the default date which is **(01–01-1970)**. This will help us know the number of days, months, and years that have elapsed.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */

    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
    //Subtract each member of our array from the default date
    const days_passed = Number(Math.abs(calcFormat[0]) - 1);
    const months_passed = Number(Math.abs(calcFormat[1]) - 1);
    const years_passed = Number(Math.abs(calcFormat[2]) - 1970);
}
```
We also need to set up a custom text that will help to prevent errors in counting like; 1 years ago or 1 months ago.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */

    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
    //Subtract each member of our array from the default date
    const days_passed = Number(Math.abs(calcFormat[0]) - 1);
    const months_passed = Number(Math.abs(calcFormat[1]) - 1);
    const years_passed = Number(Math.abs(calcFormat[2]) - 1970);

    //Set up custom text
    const yrsTxt = ["year", "years"];
    const mnthsTxt = ["month", "months"];
    const daysTxt = ["day", "days"];
}
```
Now if you [search for how many days there are in 6 months](https://www.google.com/search?q=how+many+days+are+in+6+months), you would get the formula that we will use to get the total number of days between the two dates.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1637324477318/ZUVrt7OY9.png)
 
## FINDING THE TOTAL NUMBER OF DAYS ELAPSED

Let’s find the total number of days by converting the years and months to days, then we will sum the result with the already existing days from the calculation.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */

    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
    //Subtract each member of our array from the default date
    const days_passed = Number(Math.abs(calcFormat[0]) - 1);
    const months_passed = Number(Math.abs(calcFormat[1]) - 1);
    const years_passed = Number(Math.abs(calcFormat[2]) - 1970);

    //Set up custom text
    const yrsTxt = ["year", "years"];
    const mnthsTxt = ["month", "months"];
    const daysTxt = ["day", "days"];

    //Convert to days and sum together
    const total_days = (years_passed * 365) + (months_passed * 30.417) + days_passed;
}
```
## IMPROVING THE CUSTOM TEXT

I will check if the number of years that have elapsed is equal to 1, then I will show the custom text as a **year**. For Eg 1 year.

But if the number of years that have elapsed is greater than 1, I will show the custom text as **years**. Otherwise, I will not show any value.

> Note: I used a [Tenary Operator](https://octagon.hashnode.dev/tenary-operator) to simplify the logic.

Let’s round off the total days to the nearest integer because there is a 95% possibility that the result will end up as a number with a decimal. I will use the math method `Math.round()` to achieve this, and then I will return the result as an object.

```javascript
function calcDate(date1, date2){
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */
    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
    //Subtract each member of our array from the default date
    const days_passed = Number(Math.abs(calcFormat[0]) - 1);
    const months_passed = Number(Math.abs(calcFormat[1]) - 1);
    const years_passed = Number(Math.abs(calcFormat[2]) - 1970);

    //Set up custom text
    const yrsTxt = ["year", "years"];
    const mnthsTxt = ["month", "months"];
    const daysTxt = ["day", "days"];

    //Convert to days and sum together
    const total_days = (years_passed * 365) + (months_passed * 30.417) + days_passed;

    //display result with custom text
    const result = ((years_passed == 1) ? years_passed + ' ' + yrsTxt[0] + ' ' : (years_passed > 1) ?
        years_passed + ' ' + yrsTxt[1] + ' ' : '') +
        ((months_passed == 1) ? months_passed + ' ' + mnthsTxt[0] : (months_passed > 1) ?
            months_passed + ' ' + mnthsTxt[1] + ' ' : '') +
        ((days_passed == 1) ? days_passed + ' ' + daysTxt[0] : (days_passed > 1) ?
            days_passed + ' ' + daysTxt[1] : '');

    //return the result
    return {
        "total_days": Math.round(total_days),
        "result": result.trim()
    }
}
```
## TESTING THE CODE

I will use the dates below:

- date 1 = today (m-d-y) = 11-19-2021
- date 2 = future (m-d-y) = 12-12-2026

```javascript
//Call the function
calcDate("11-19-2021", "12-12-2026");
```

This is the output

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1637325721613/Y0TiQX8_Q.png)

We have 5 years and 23 days left till the 12th of December 2026.

Now if you use an external App like  [time and date](https://www.timeanddate.com/) for the same calculation, you would get if not approximate, the same value.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1637325835492/bIefXWCkM.png)

## EXTENDING THE CALCULATOR

Since we are able to calculate the total days that have elapsed, we can extend the calculator to calculate the;

- total number of seconds
- total number of minutes
- total number of hours and
- total number of weeks

```javascript
function calcDate(date1, date2) {
    /*
    * calcDate() : Calculates the difference between two dates
    * @date1 : "First Date in the format MM-DD-YYYY"
    * @date2 : "Second Date in the format MM-DD-YYYY"
    * return : Array
    */

    //new date instance
    const dt_date1 = new Date(date1);
    const dt_date2 = new Date(date2);

    //Get the Timestamp
    const date1_time_stamp = dt_date1.getTime();
    const date2_time_stamp = dt_date2.getTime();

    let calc;

    //Check which timestamp is greater
    if (date1_time_stamp > date2_time_stamp) {
        calc = new Date(date1_time_stamp - date2_time_stamp);
    } else {
        calc = new Date(date2_time_stamp - date1_time_stamp);
    }
    //Retrieve the date, month and year
    const calcFormatTmp = calc.getDate() + '-' + (calc.getMonth() + 1) + '-' + calc.getFullYear();
    //Convert to an array and store
    const calcFormat = calcFormatTmp.split("-");
    //Subtract each member of our array from the default date
    const days_passed = Number(Math.abs(calcFormat[0]) - 1);
    const months_passed = Number(Math.abs(calcFormat[1]) - 1);
    const years_passed = Number(Math.abs(calcFormat[2]) - 1970);

    //Set up custom text
    const yrsTxt = ["year", "years"];
    const mnthsTxt = ["month", "months"];
    const daysTxt = ["day", "days"];

    //Convert to days and sum together
    const total_days = (years_passed * 365) + (months_passed * 30.417) + days_passed;
    const total_secs = total_days * 24 * 60 * 60;
    const total_mins = total_days * 24 * 60;
    const total_hours = total_days * 24;
    const total_weeks = (total_days >= 7) ? total_days / 7 : 0;

    //display result with custom text
    const result = ((years_passed == 1) ? years_passed + ' ' + yrsTxt[0] + ' ' : (years_passed > 1) ?
        years_passed + ' ' + yrsTxt[1] + ' ' : '') +
        ((months_passed == 1) ? months_passed + ' ' + mnthsTxt[0] : (months_passed > 1) ?
            months_passed + ' ' + mnthsTxt[1] + ' ' : '') +
        ((days_passed == 1) ? days_passed + ' ' + daysTxt[0] : (days_passed > 1) ?
            days_passed + ' ' + daysTxt[1] : '');

    //return the result
    return {
        "total_days": Math.round(total_days),
        "total_weeks": Math.round(total_weeks),
        "total_hours" : Math.round(total_hours),
        "total_minutes" : Math.round(total_mins),
        "total_seconds": Math.round(total_secs),
        "result": result.trim()
    }
}
```
So when I call the function to calculate the date difference between today (08–04–2022) and the same future date (12–12–2026), this is the result.

![time & date calculator javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tut58qh8mnjhlwc509o.png)
 
So from the calculation, we still have 4 years, 4 months & 10 days left till the 12th of December 2026.

## CONCLUSION

So that’s a basic setup for a function that helps to calculate the difference between two dates.

You have reached the end of my article.

## EXTRA

I recently launched a JavaScript package that validates your HTML forms using validation rules, regular expressions and form input attributes.

I will appreciate if you spared a few seconds to check it out.

{% embed https://github.com/octagon-simon/octaValidate/ %}

Thank You