How to get difference between two dates in javascript?


I would like to get Difference between two dates using javascript or jQuery in simple way.

How can I do that, for example

var date1 = new Date('22/03/2018');
var date2 = new Date('25/04/2018');
var diffOfDays = date2.getDate().Days - date1.getDate().Days; 
console.log(diffOfDays);

Any simple working fiddle example? Thanks


Asked by:- bhanu
2
: 3455 At:- 3/22/2018 12:50:42 PM
javascript date difference







3 Answers
profileImage Answered by:- Sam

You can use the below function which

diffrenceindays();

function diffrenceindays() {
    var startfield = new Date(2018, 3, 24);
    var endfield = new Date(2018, 3, 27);
    var startdate = GetDateValue(startfield);
    var Enddate = GetDateValue(endfield);

    var oneday = 1000 * 60 * 60 * 24;
    var differenceInDays = ((Enddate - startdate) / oneday);
    if (differenceInDays < 0) {
        alert(" date cannot be less then start date");

    }
    alert(" diffrence in days  " + differenceInDays);

}

function GetDateValue(field) {
    var year = field.getFullYear();
    var month = field.getMonth();
    var day = field.getDate();
    dateOnly = new Date(year, month, day);
    return dateOnly;


}

I have created a fiddle, take a look https://jsfiddle.net/3mauc5ns/3/

OR

Simply use Math.abs and ceil methods of Javascript to get date difference

const date1 = new Date('7/13/2022');
const date2 = new Date('12/15/2022');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");

Output:

"13392000000 milliseconds"
"155 days"

Fiddle: https://jsfiddle.net/kr31L7hx/

Thanks.

3
At:- 3/23/2018 6:52:24 AM Updated at:- 12/12/2022 5:52:27 AM
Thanks 0
By : bhanu - at :- 3/29/2018 11:55:55 AM


profileImage Answered by:- pika

You can easily get the difference between two dates if you are using Moment.js

    var a = moment('1/1/2012', 'DD/MM/YYYY');
    var b = moment('1/1/2013', 'DD/MM/YYYY');
    var days = b.diff(a, 'days');
    // days == 366

Here is the working fiddle  for testing.

2
At:- 3/29/2018 9:27:30 AM


profileImage Answered by:- jon

Check difference between 2 dates in Javascript using code below

var date1 = new Date("7/11/2021");
var date2 = new Date("10/11/2021");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

console.log(diffDays)

OR

Use moment.js

var a = moment('7/11/2022','M/D/YYYY');
var b = moment('12/15/2022','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);

Thanks.

1
At:- 6/23/2022 7:11:33 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use