Home > OS >  Check if the current time with day is between 2 dates in a weekly calendar
Check if the current time with day is between 2 dates in a weekly calendar

Time:09-04

There are a ton of different node modules that lets you check if a date is between two other dates. But I cannot find any modules that let me do the same for day and time (without the date). I only have a weekly calendar (Monday - Sunday) and I want to check if a current day (with time) is between two other days (with time without the date).

Example:
If "now" is Saturday 11:25

Return true if "now" is between Friday 16:00 and Monday 08:00
Return true if "now" is between Saturday 11:00 and Saturday 12:00

Return false if "now" is between Monday 08:00 and Friday 16:00
Return false if "now" is between Wednesday 08:00 and Saturday 10:00

Are there any easy solution for this?

CodePudding user response:

The question is whether "now" can be placed between two given points in time that are not more than a week apart.

The following functions work on "date objects" consisting of a day (Sunday = 0, Monday = 1, ..., Saturday = 6) and a time. The between function tries to sort start <= now <= end after shifting by one week where necessary. It returns true if that is successful.

function before(a, b) {
  return a.day < b.day ||
         a.day === b.day && a.time < b.time;
}
function oneweeklater(date) {
  return {day: date.day   7, time: date.time};
}
function between(now, start, end) {
  if (before(end, start)) end = oneweeklater(end);
  if (before(now, start)) now = oneweeklater(now);
  return !before(end, now);
}
var now = {day: 6, time: "11:25"};
console.log(between(now, {day: 5, time: "16:00"}, {day: 1, time: "08:00"}),
            between(now, {day: 6, time: "11:00"}, {day: 6, time: "12:00"}),
            between(now, {day: 1, time: "08:00"}, {day: 5, time: "16:00"}),
            between(now, {day: 3, time: "08:00"}, {day: 6, time: "10:00"}));

CodePudding user response:

I would use moment.js plugin: https://momentjs.com/

let now = moment('6 11:25', 'E HH:mm');
let min = moment('5 16:00', 'E HH:mm');
let max = moment('1 08:00', 'E HH:mm');

if(max.isBefore(min))
  max.add(1, 'weeks');

if(now.isBefore(min))
  now.add(1, 'weeks');

console.log(now.isBetween(min, max));
<script src="https://momentjs.com/downloads/moment.js"></script>

  • Related