How to check time range in javascript

I have a start and end time along with a date.

stime:1pm , etime:2pm , date:2/6/2013 

I want to save this time and start and end date in mongodb. therefore, before saving this information

I have to check within this date whether this time range exists or not

so how to do it in javascript. How to check the time range already exists or not?

I tried how this.but is not working properly. even I don’t know my approach, right or wrong?

I hope someone helps me find a solution to 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"); } 
+4
source share
2 answers

Use a timestamp instead of a Date object to effectively compare ranges. It will also be much more efficient for indexing a database by timestamp. If you don’t know what time is earlier in a couple of dates for time intervals, you can perform min and max checks. But if you know what time before and after, no min , max in state is required.
The condition below checks if the time frame is Overlapping , which means that it will be true , even if only the second second of the first time overlaps with the first second from the second time.
You can perform other checks for Contain and determine which one contains, but this is a 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 } 
+9
source

I have another solution for this, we can use Moment-range, which is a plugin for Moment.js

Just check this moment-range .

check fiddle

 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 
0
source

Source: https://habr.com/ru/post/1488659/


All Articles