Reputation: 1457
i have start and end time along with date.like this
stime:1pm , etime:2pm , date:2/6/2013
i want to store this start and end time and date into mongodb. so before saving this details
, i should check within this date, this time range is exist or not
so how to do that in javascript. how to check time range already exist or not?
i have tried like this.but it is not working properly. even i don't know my approach ,whether right or wrong ?
i hope that anyone help me to find solution for this.
var d0 = new Date("01/01/2001 " + "8:30 AM");
var d1 = new Date("01/01/2001 " + "9:00 PM");
var d2 = new Date("01/01/2001 " + "8:30 AM");
var d3 = new Date("01/01/2001 " + "9:00 PM");
if(d2<d0&&d3<=d0||d2<d1&&d3<=d3)
{
console.log("available");
}else{
console.log("not available");
}
Upvotes: 9
Views: 32621
Reputation: 1813
i have another solution for that, we can use Moment-range which is plugin for Moment.js
Just check this Moment Range .
var start = new Date(2012, 4, 1);
var end = new Date(2012, 4, 23);
var lol = new Date(2012, 4, 15);
var wat = new Date(2012, 2, 27);
var range = moment().range(start, end);
var range2 = moment().range(lol, wat);
range.contains(lol); // true
range.contains(wat); // false
Upvotes: 3
Reputation: 23047
Use timestamp instead of Date object in order to efficiently compare ranges. This as well will be much more efficient for Database to index by timestamp.
If you don't know which of time is earlier in pair of dates for timespans, then you can do min
and max
checks. But if you do know which time is before and which after, no min
, max
in condition required.
Condition bellow checks if timespans Overlap which means it will be true
even if only last second of first timespan overlaps with first second from second timespan.
You can do other checks for Contain and identify which of them contain which, but thats different condition.
// time of first timespan
var x = new Date('01/01/2001 8:30:00').getTime();
var y = new Date('01/01/2001 9:30:00').getTime();
// time of second timespan
var a = new Date('01/01/2001 8:54:00').getTime();
var b = new Date('01/01/2001 9:00:00').getTime();
if (Math.min(x, y) <= Math.max(a, b) && Math.max(x, y) >= Math.min(a, b)) {
// between
}
Upvotes: 14