Control of schedules with moment js

1

In my timetable control code, I check if the current time is within the range of opening time and closing time. This is my code:

var ha = moment("00:00:00", 'H:mm:ss');
  var hc = moment("23:59:00", 'H:mm:ss');
  var hactual = moment("00:00:00", 'H:mm:ss');

  var h_apertura = ha.format('HH:mm:ss');
  var h_cierre = hc.format('HH:mm:ss');
  var h_actual = hactual.format('HH:mm:ss');

  if(h_apertura <= h_actual && h_actual <= h_cierre){
    alert("ABIERTO \nhora de apertura: "+h_apertura+"\nhora de cierre: "+h_cierre+"\nhora actual:"+h_actual);
    }else{
    alert("CERRADO \nhora de apertura: "+h_apertura+"\nhora de cierre: "+h_cierre+"\nhora actual:"+h_actual);
  }

in the control code that 00:00 is within the range of 00:00 and 23:59, my question is:

Is it possible for a company to open its business at 09:00 and close at 02:00 in the morning? if this is how I would do that control

I thank you in advance for your answers I attach my jsfiddle

    
asked by Dimoreno 07.08.2018 в 06:31
source

1 answer

4

The library moment.js is designed to work with dates, not with simple hours, so I think it is not the best solution. It is very easy to do the checks manually:

function formateaMomento(momento) {
  const regexp=/\d\d:\d\d(:\d\d)?/;
  if (regexp.test(momento)) {
    const units=momento.split(':');
    return ((+units[0]) * 3600) + (+units[1] * 60) + (+units[2] || 0);
  }
  return null;
}

console.log(formateaMomento('09:30'));

function generadorHorario(horaApertura,horaCierre) {
  let a=formateaMomento(horaApertura);
  let c=formateaMomento(horaCierre);
  
  console.log('horario: de',a,'a',c);
     
  return function (hora) {
    const h=formateaMomento(hora);
    
    //abierto a las 00:00
    if (a>c) {
      return (h >= a || h <= c);
    }
    
    return (h>=a && h<= c);
  }

}

let abiertoFn=generadorHorario('09:00','02:00');


console.log(abiertoFn('08:00'));
console.log(abiertoFn('23:00'));

let abiertoFn2=generadorHorario('09:00','23:00');
console.log(abiertoFn2('24:00'));
console.log(abiertoFn2('19:00'));
  • The first function goes to an absolute value at a given time (seconds passed since midnight).
  • The second function generates a time checker: given the time of opening and closing, it creates a new function that verifies that a given moment is within opening hours.
answered by 07.08.2018 в 10:00