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
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.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly