最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

date - How to check time between range using javascript - Stack Overflow

programmeradmin4浏览0评论

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

I want to do a checking using two IF condition

  1. if the time value is between 05:00 to 22:00
  2. if the time value is between 22:00 to 05:00

I am not sure how to do that.

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

I want to do a checking using two IF condition

  1. if the time value is between 05:00 to 22:00
  2. if the time value is between 22:00 to 05:00

I am not sure how to do that.

Share Improve this question asked Jul 20, 2017 at 4:06 aslamdoctoraslamdoctor 3,94512 gold badges57 silver badges103 bronze badges 4
  • 1 could you show us, what did you tried so far ? – Ravi Commented Jul 20, 2017 at 4:08
  • Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to try to solve your own problem first. Please update your question to show what you have already tried, showcasing all of your relevant code in a minimal, plete, and verifiable example. – Obsidian Age Commented Jul 20, 2017 at 4:09
  • Possible duplicate of check if one date is between two dates (javascript) – Ravi Commented Jul 20, 2017 at 4:10
  • @Ravi—the OP doesn't have dates and doesn't need them. – RobG Commented Jul 20, 2017 at 4:23
Add a ment  | 

2 Answers 2

Reset to default 6

Since times in HH:mm format can be pared directly, you just need to pare 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(' - '));
});

To provide more robust code, the input should be validated and cases over midnight should be considered.

Validation should limit hours to the range 00-23 and minutes to the range 00 to 59, e.g.

/^(([0-1][0-9])|(2[0-3])):[0-5][0-9]$/.test(time)

If the start time is less than the end time, assume that the range doesn't go over midnight, e.g. 05:00 to 22:00. If the start is greater than the end, the range does go over midnight, so:

function isInRange(value, range) {
  let re = /^(([0-1][0-9])|(2[0-3])):[0-5][0-9]$/;
  let [start, end] = range;
  // Validate values
  if ([value, start, end].some(value => !re.test(value))) {
    return;
  }

  // If start less than end, assume doesn't go over midnight
  if (start <= end) {
    return value >= start && value < end;
  
  // Otherwise, assume goes over midnight
  } else {
    return value >= start || value < end;
  }
}


// Range on same day midnight
let range = ['05:00', '22:00'];
['08:30','23:00','25:15'].forEach(value => {
  let inRange = isInRange(value, range);
  // Check returned value isn't undefined
  if (inRange === void 0) {
    console.log(`Invalid input: ${value}, [${range}]`);
  } else {
    console.log(`${value}: is ${inRange? '':'not'} in [${range}]`);
  }
});

// Range over midnight
range = ['22:00', '05:00'];
['08:30','23:00'].forEach(value => console.log(
 `${value}: is ${isInRange(value, range)? '':'not'} in [${range}]`
 ));

If paring strings doesn't suit, times can be reduced to a mon unit, say minutes and then pared, e.g.

// Convert time in H:mm format to minutes
function timeToMins(time) {
  let re = /^(([0-1]?[0-9])|(2[0-3])):[0-5][0-9]$/;
  if (!re.test(time)) return;
  let [H, m] = time.split(':');
  return H * 60 + m * 1;
}

function isInRange(time, range) {
  // Input validation
  let re = /^(([0-1]?[0-9])|(2[0-3])):[0-5][0-9]$/;
  if ([time, ...range].some(time => !re.test(time))) {
    return;
  }
  // Convert times to minutes
  let [start, end] = range.map(time => timeToMins(time));
  time = timeToMins(time);

  // If start less than end, assume doesn't go over midnight
  if (start <= end) {
    return time >= start && time < end;

    // Otherwise, assume goes over midnight
  } else {
    return time >= start || time < end;
  }
}

// Range on same day midnight
let range = ['05:00', '22:00'];
['08:30', '23:00', '25:15'].forEach(value => {
  let inRange = isInRange(value, range);
  // Check returned value isn't undefined
  if (inRange === void 0) {
    console.log(`Invalid input: ${value}, [${range}]`);
  } else {
    console.log(`${value}: is ${inRange? '':'not'} in [${range}]`);
  }
});

// Range over midnight
range = ['22:00', '05:00'];
['08:30', '23:00'].forEach(value => console.log(
  `${value}: is ${isInRange(value, range)? '':'not'} in [${range}]`
));

Try this code snippet

function dateObj(d) {
    var parts = d.split(":"),
        date  = new Date();

    date.setHours(parts[0]);
    date.setMinutes(parts[1]);
    return date;
}
if(dateObj('02:35')>= dateObj('14:30')&& dateObj('14:30')<=dateObj('22:00'))alert('true');
发布评论

评论列表(0)

  1. 暂无评论