Knowing if a time period (hour) makes sense

Asked

Viewed 30 times

0

The user will type a period in hours and it has to make sense. For example, he can say that he will be charged an on-call fee between 22:00 and 6:00 , that may be, but he can’t say for example that the on-call is between 4:00 and 3:00 obviously. The solution I found was the following, but it’s very complex, I’m sure you can do better, Javascript does not have a function ready to compare hours? Thank you.

          var mensagem='tudo ok';
          var hi='10:00';
          var hf='11:30';

          var hora_inicial=hi.substring(0,2);
          var hora_final=hf.substring(0,2);
          var minuto_inicial=hi.substring(3,5);
          var minuto_final=hf.substring(3,5);

         var mesmo_grupo=0; //saber se estão no mesmo grupo am ou pm

         if (hora_inicial >= 12 && hora_inicial<=24 && hora_final>=12 && hora_final<=24 )
         mesmo_grupo=1;

         if (hora_inicial >=0 && hora_inicial<=12 && hora_final >=0 && hora_final<=12)
         mesmo_grupo=1;

           if (mesmo_grupo==1)  //se  estão no mesmo am ou pm a primeira hora tem que ser menor que a segunda
         {

            if (hora_inicial > hora_final)
             {
             continua=0;
             mensagem='Reveja a hora. ';            
             }

         }
alert(mensagem);
  • 2

    Why can’t you give 4 to 3 if the guy can turn into a day on duty?

  • In fact he attends people in a time of duty and charges a fee, for example, a doctor attends you until 22:00 for R$300 the appointment and from 22:00 to 6:00 for R$500 for charging a fee of R$200 on duty. Mathematically it would make sense your exposure but not in practice.

1 answer

1

What I would do is define that a shift should be at most X hours, and validate whether the amount of time subtraction is greater than the duty limit.

//Retorna true se válido
function validaPlantao(hora1, hora2)
{
    var plantaoLimite = 12; 
    var hora = 60000 * 60; 
    
    hora1 = hora1.split(":");
    hora2 = hora2.split(":");
    
    var d = new Date();
    var data1 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora1[0], hora1[1]);
    var data2 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora2[0], hora2[1]);
    var resultado = (data2 - data1) / hora ; 
    return resultado < plantaoLimite;
};

console.log(validaPlantao('07:00', '18:00'));
console.log(validaPlantao('08:30', '19:00'));
console.log(validaPlantao('00:00', '23:00'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.