简体   繁体   English

如何在javascript中检查时间范围

[英]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.我想将此开始和结束时间和日期存储到 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.那么如何在 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");
 }

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.如果您不知道时间跨度的日期对中哪个时间更早,那么您可以进行minmax检查。 But if you do know which time is before and which after, no min , max in condition required.但是,如果您确实知道哪个时间在之前和之后,则不需要minmax条件。
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.下面的条件检查时间跨度是否重叠,这意味着即使第一个时间跨度的最后一秒与第二个时间跨度的第一秒重叠,它也会为true
You can do other checks for Contain and identify which of them contain which, but thats different condition.您可以对Contain进行其他检查,并确定其中哪些包含哪些,但这是不同的条件。

// 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
}

i have another solution for that, we can use Moment-range which is plugin for Moment.js我有另一个解决方案,我们可以使用 Moment-range,它是 Moment.js 的插件

Just check this Moment Range .只需检查此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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM