Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check time range in javascript

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");
 }
like image 266
silvesterprabu Avatar asked Jun 28 '13 10:06

silvesterprabu


1 Answers

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
}
like image 56
moka Avatar answered Oct 28 '22 17:10

moka