LATEST >>

Welcome Here And Thanks For Visiting. Like Us On Facebook...

# Get Difference In Two Dates In Days, Hours, Minutes And Seconds In JavaScript

Today, we will learn to calculate the time difference between two dates in days, hours, minutes, and seconds. Either you are receiving values in the JS variable, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes, and seconds in leading zeroes.

Basically, we are going to get the difference between the current date and the date in the future. Then we will extract the days, hours, minutes, and hours from that difference. The difference will be in seconds so we have to apply some math to it.

There are many code snippets available online or on many other blogs and websites, but everyone cannot optimize your blog or website, so you need some optimized code snippets. So now checkout out the code snippet for your blog and website that will give you all features for your desired code. Now grab the ready-to-use code and paste it where you want.

## Features:

1. Light Weight.
2. Pure Vanilla JavaScript Code.
3. No External Files.
4. Work With Any Format Of Date.
5. Fully Customizable.
Recommended For You:
How To Add Opacity On Background Image Using CSS?

## How To Get Difference In Two Dates In Days, Hours, Minutes And Seconds In JavaScript?

There are a few easy and understandable steps to achieve your desired functionality using pure PHP that we are gonna share below. Follow each step perfectly.

### JavaScript:

```/**
* Function: Find the Difference in DateTime
* @param {String, String} ==>> ("2022-11-31 23:59:59", "2022-11-01 23:59:59")
* @return {Object} ==>> { diff: 131400000, d: 2, h: 13, m: 30, s: 0, ms: 0 }
* Developed by: Muhammad Hassan
*/
function dateDiff( str1, str2 ) { //return { diff: 131400000, d: 2, h: 13, m: 30, s: 0, ms: 0 }
var diff = Date.parse( str1 ) - Date.parse( str2 );
return isNaN( diff ) ? NaN : {
diff : diff,
ms : Math.round( diff % 1000 ),
s : Math.round( diff / 1000 % 60 ),
m : Math.round( diff / 60000 % 60 ),
h : Math.round( diff / 3600000 % 24 ),
d : Math.round( diff / 86400000 )
};
}```

## Customization:

No need to customize it. Just copy-paste. Rest edit the code as per comments and need.

## Troubleshooting the Errors:

Do it with concentration and patience. Check your all steps again and all codes or scripts. If you find any error you can contact us anytime via comment or better via email, We are always here to help you.

## Final Words:

Recommended For You:
How To Add Rainbow Animation Into Header Logo Or Text?