Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two dates are more than 7 days apart using moment.js

I'm trying to determine whether there are more than 7 days between two dates using moment.js.

code:

var start = moment(self.StartDate(), "DD/MM/YYYY");
var end = moment(self.EndDate(), "DD/MM/YYYY");

console.log(start);
console.log(end);
console.log(moment.duration(end.diff(start)).asDays());

if (moment.duration(end.diff(start)).asDays() > 7) {
    alertify.alert("Error", "Only a maximum of 7 days can be investigated.");
    return;
}

This works if the two dates are within the same month. However, if the dates cross over between 2 months the duration returns a negative value.

Example results:

enter image description here

like image 219
Bhav Avatar asked Jun 25 '19 08:06

Bhav


1 Answers

Use diff method to check difference between two days and add days as second parameter to get difference in days.

var d1 = "2019-01-10";
var d2 = "2019-01-20";
var diff = moment(d2).diff(d1, 'days')
alert('difference :' + diff)

alert('is difference more than 7: ' + (diff > 7))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
like image 127
Neel Bhanushali Avatar answered Nov 07 '22 09:11

Neel Bhanushali