如何使用JavaScript检查范围之间的时间 [英] How to check time between range using javascript

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

问题描述

我的时间值是 HH:MM 格式。小时为24小时格式。
例如14:30

I have the time value in HH:MM format. Hours are in 24 hours format. e.g. 14:30

我要使用两个IF条件进行检查

I want to do a checking using two IF condition


  1. 如果时间值在05:00到22:00之间

  2. 如果时间值在22:00到05:00之间

我不确定该怎么做。

推荐答案

自HH:mm起格式可以直接进行比较,您只需要比较值即可。如果时间在范围内,则以下代码返回true,否则返回false。

Since times in HH:mm format can be compared directly, you just need to compare the values. The following returns true if the time is in range, false otherwise.

var range = ['05:00','22:00'];

function isInRange(value, range) {
  return value >= range[0] && value <= range[1];
}

['04:59','08:30','23:15'].forEach(function(time) {
  console.log(time + ' is ' + (isInRange(time, range)? ' ':'not ') + 'in range');
});

// Alternatively
['04:59','23:15','08:30'].forEach(function(time) {
  var inRange = isInRange(time, range);
  console.log(time + ' is in range ' + (inRange? range : range.slice().reverse()).join(' - '));
});

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

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