当前位置:主页 > 网页前端 > JavaScript代码 >

js 判断所选时间(或者当前时间)是否在某一时间段的实现代码

时间:2021-07-12 13:28:35 | 栏目:JavaScript代码 | 点击:

核心代码:

var time_range = function (beginTime, endTime, nowTime) {
  var strb = beginTime.split (":");
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split (":");
  if (stre.length != 2) {
    return false;
  }

  var strn = nowTime.split (":");
  if (stre.length != 2) {
    return false;
  }
  var b = new Date ();
  var e = new Date ();
  var n = new Date ();

  b.setHours (strb[0]);
  b.setMinutes (strb[1]);
  e.setHours (stre[0]);
  e.setMinutes (stre[1]);
  n.setHours (strn[0]);
  n.setMinutes (strn[1]);

  if (n.getTime () - b.getTime () > 0 && n.getTime () - e.getTime () < 0) {
    return true;
  } else {
    alert ("当前时间是:" + n.getHours () + ":" + n.getMinutes () + ",不在该时间范围内!");
    return false;
  }
}
time_range ("21:30", "23:30", "3:22");

效果:

当前时间的情况下:

var time_range = function (beginTime, endTime) {
  var strb = beginTime.split (":");
  if (strb.length != 2) {
    return false;
  }

  var stre = endTime.split (":");
  if (stre.length != 2) {
    return false;
  }

  var b = new Date ();
  var e = new Date ();
  var n = new Date ();

  b.setHours (strb[0]);
  b.setMinutes (strb[1]);
  e.setHours (stre[0]);
  e.setMinutes (stre[1]);

  if (n.getTime () - b.getTime () > 0 && n.getTime () - e.getTime () < 0) {
    return true;
  } else {
    alert ("当前时间是:" + n.getHours () + ":" + n.getMinutes () + ",不在该时间范围内!");
    return false;
  }
}
time_range ("21:30", "23:30");

您可能感兴趣的文章:

相关文章