如何在javascript中检查时间范围 [英] how to check time range in javascript

查看:90
本文介绍了如何在javascript中检查时间范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有开始和结束时间以及date.like this

i have start and end time along with date.like this

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

我想将此开始和结束时间和日期存储到mongodb中。所以在保存这个细节之前

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

所以如何在javascript中做到这一点。如何检查时间范围是否已经存在?

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");
 }


推荐答案

使用timestamp而不是Date对象为了有效地比较范围。这也是数据库按时间戳索引的效率更高。

如果你不知道时间跨度的日期对应的早些时候,你可以做 min max 检查。但是如果您确实知道之前和之后的时间,在需要的条件下没有 min max

条件波纹管检查时间间隔重叠,这意味着它将 true 即使只是第一个时间跨度的最后一秒与第二个时间段的第一秒重叠时间跨度。

您可以对包含进行其他检查,并确定哪些包含哪些,但条件不同。

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
}

这篇关于如何在javascript中检查时间范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆