days between dates code example
Example 1: calculate days between dates
let startDate = "2021-04-01";
let date1 = new Date();
let date2 = new Date(startDate);
let timeInMilisec = date1.getTime() - date2.getTime();
let daysBetweenDates = Math.ceil(timeInMilisec / (1000 * 60 * 60 * 24));
Example 2: date difference
function daysBetween(first, second) {
var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;
return Math.floor(days);
}
Example 3: get days between two dates
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
alert(datediff(parseDate(first.value), parseDate(second.value)));