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
1
: 281 At:- 3/22/2018 12:50:42 PM
javascript date difference






2 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/

3
At:- 3/23/2018 6:52:24 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.

1
At:- 3/29/2018 9:27:30 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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly