I have tried all the solutions in the stack overflow, but couldn't find the exact solution or answer for my question.Some times it shows negative values when i tried to convert the date using getTime(), and sometimes the number of days showed in the answers seems to be incorrect compared to the manually calculated one. I've added the code that've used for my calculation. Please make a look.
Referred : Difference between two dates in years, months, days in JavaScript
var date2 = new Date("2018-01-01");
var date1 = new Date("2017-01-01");
var diff = Math.floor(date2.getTime() - date1.getTime());
//1000*60*60*24
var secs = Math.floor(diff / 1000);
var mins = Math.floor(secs / 60);
var hours = Math.floor(mins / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 31);
var years = Math.floor(months / 12);
months = Math.floor(months % 12);
days = Math.floor(days % 31);
hours = Math.floor(hours % 24);
mins = Math.floor(mins % 60);
secs = Math.floor(secs % 60);
var message = "";
if (days <= 0) {
message += secs + " sec ";
message += mins + " min ";
message += hours + " hours ";
} else {
message += days + " days ";
if (months > 0 || years > 0) {
message += months + " months ";
}
if (years > 0) {
message += years + " years ago";
}
}
console.log(message);
//Expected result is : 1 year 0 months 0 days.
//Actual result is : 11 months 24 days.