Could you point how to correctly validate if the time before the date/ time filled on the textbox is greater or equal 03 hours?

Eduardo Fuerte
Eduardo Fuerte used Ask the Experts™
on
Hi Experts

Could you point how to correctly validate if the time before the date/ time filled on the textbox is greater or equal 03 hours?

Accordingly to:
img002
<td id="div_data_missao_ida_1" style="visibility: <?=(isset($guia['missao'][0]['nMissaoPreMarcada']) && $guia['missao'][0]['nMissaoPreMarcada']==1 ?"visible":"visible")?>;">
	<label class="form_title">Data da Miss&atilde;o:</label><br/>
	<input type="text"  class="input" name="dpremarcada_ida" id="dpremarcada_ida" value="<?=(isset($guia['missao'][0]['dMissao'])?formataStamp($guia['missao'][0]['dMissao'],"stamp","dma"):date("d/m/Y"))?>" size="11" maxlength="10"  onchange="copiaDataMissaoTIT();">
	<img src="imagens/calendario.png" name="cal_trigger" id="cal_trigger" border="0" align="absmiddle" onmouseover="javascript: calendar_param('dpremarcada_ida', 'cal_trigger', isAnterior);" style="cursor: pointer;" >
</td>


<td id="div_data_missao_ida_2" style="visibility: <?=(isset($guia['missao'][0]['nMissaoPreMarcada']) && $guia['missao'][0]['nMissaoPreMarcada']==1 ?"visible":"visible")?>;">
	<label class="form_title">Hor&aacute;rio:</label><br/>
	<input type="text"  onkeypress="campo_hora(event); return validaDigNum(event);" value="<?=(isset($guia['missao'][0]['dMissao'])?formataStamp($guia['missao'][0]['dMissao'],"stamp","hm"):date("H:i"))?>" size="5" maxlength="5" name="horario_premarcada_ida" id="horario_premarcada_ida" class="input" >            
</td>

Open in new window


The dtae/ time filled in the textbox must to be greater than 03 hours.

Could you suggest how to solve?

Thanks in advance
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
You have not said where your controls are located.

If they are in a form then you can do this on submit (otherwise on whatever event you want to do the validation)
1. Get the date string from the date input, get the time string from the time input. Concatenate them to get a date time string
var datestr = $('#id_date_input').val();
var timestr = $('#id_time_input').val();

Open in new window

2. Create a new date object from this time string
var datetime  = new Date(datestr + ' ' + timestr);

Open in new window

3. Now get the current time
var now = Date.now();

Open in new window

4. Finally check the difference in hours (time values are in ms so we divide by 3600 x 1000)
if ((datetime.getTime() - now) / (3600 * 1000)) > 3) {
   alert('Date / Time is invalid');
}

Open in new window


Working sample here
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi @Julian

The code runs at front-end.
I'm looking your solution, but the working sample is missed.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Sorry Eduardo,

The link text was overwritten in my original post  I have fixed the post and posted the URL here again

http://www.marcorpsa.com/ee/t3504.html
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi @Julian

The server where the example runs seens not working out today.
Could you give a look?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Ok. Now.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Could you check what is going wrong on my case?
img001
Adapted to my case
function pre_salvar_captacao_tit(validaAnteriores) {
  try {
    
    
      var now = Date.now();
      var d1 = document.getElementById('dpremarcada_ida_stacasa').value;
      var t1 = document.getElementById('horario_premarcada_ida_stacasa').value;   


      var formtime = new Date(d1 + ' ' + t1);

      console.log('XXXX');
      console.log(now);
      
      console.log(d1);
      console.log(t1);
      
      console.log(formtime);
      
      
      
     if (  ( (formtime.getTime() - now) / 3600000)   < 3   )   {
            alert('Agendar com no mínimo 03 horas de antecedencia');
     }      
     else
     {
         alert('Agendar com no mínimo 03 horas de antecedencia');
    }

Open in new window



 alert('Agendar com no mínimo 03 horas de antecedencia');  is always fired  even if the hour is later than 03 hours.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
I just tested your code in my sample and it seems to work fine.

You can see it working here
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
.... but then I did notice that your Alerts have the same message
if (  ( (formtime.getTime() - now) / 3600000)   < 3   )   {
  alert('Agendar com no mínimo 03 horas de antecedencia'); // HOW IS THIS 
}      
else {
  alert('Agendar com no mínimo 03 horas de antecedencia'); // DIFFERENT FROM THIS ??????
}

Open in new window

Eduardo FuerteDeveloper and Analyst

Author

Commented:
Sorry

     if (  ( (formtime.getTime() - now) / 3600000)   < 3  )   {
            alert('Agendar com no mínimo 03 horas de antecedencia');
     }      
     else
     {
         alert('Agendamento OK');
    }

Open in new window


Even if the time difference is lower than 3 hours
alert('Agendamento OK');
is fired.

I don't know why the console stoped running.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
The value is never <3

img002

     console.log('h1');
      var h1 = (formtime.getTime()) / 3600000
      console.log(h1);
            
      console.log('h2');
      var h2 = ( now) / 3600000
      console.log(h2);             
       

      var teste = (formtime.getTime() - now) / 3600000
      console.log('Teste');
      console.log(teste);
      
      
     if (  ( (formtime.getTime() - now) / 3600000)   < 3  )   {
            alert('Agendar com no mínimo 03 horas de antecedencia');
     }      
     else
     {
         alert('Agendamento OK');
    }

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
If you look at my latest sample - it implements your function AND mine - yours is called after. As you can see from that sample it works.

So this is probably something on your side that you are not showing here?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Really.

I don´t know why the date/ time is converted 3 hours later...

JS:
function pre_salvar_captacao_tit(validaAnteriores) {
  try {
    
        var now = Date.now();
        
        var d1 = document.getElementById('dpremarcada_ida_stacasa').value;
        var t1 = document.getElementById('horario_premarcada_ida_stacasa').value;   


        console.log('d1');
        console.log(d1);

        console.log('t1');
        console.log(t1);


      //var formtime = new Date(this.date.value + ' ' + this.time.value);
       var formtime = new Date(d1 + ' ' + t1);

       console.log('formtime');
       console.log(formtime);

Open in new window


img003
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Because getTime() returns UTC time - your timezone is what is creating the difference.

Where are you based? This is suggesting you are somewhere west of Greenwhich (GMT-3) - is that correct?

The algorithm should still work though - because both times are in UTC - so the hour difference should still work out.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Well...
In the meanwhile I did this workaround
function pre_salvar_captacao_tit(validaAnteriores) {
  try {
    
        var now = Date.now();
        
        var d1 = document.getElementById('dpremarcada_ida_stacasa').value;
        var t1 = document.getElementById('horario_premarcada_ida_stacasa').value;   

       // This formats correctly what is presented at the form:
        var data = new Date(),
        dia  = data.getDate().toString(),
        diaF = (dia.length == 1) ? '0'+dia : dia,
        mes  = (data.getMonth()+1).toString(), //+1 pois no getMonth Janeiro começa com zero.
        mesF = (mes.length == 1) ? '0'+mes : mes,
        anoF = data.getFullYear();
       
        formtime = new Date(anoF+"/"+mesF+"/"+diaF+ ' ' + t1);

      
     if (  ( (formtime.getTime() - now) / 3600000)   < 3  )   {
            alert('Agendar com no mínimo 03 horas de antecedencia');
     }      
     else
     {
         alert('Agendamento OK');
    }

Open in new window


So, it finally runs:

Difference of time greather than 03 hours => OK
img004
Difference of time less than 03 hours => NOK
img005
Well, it's running correctly.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
That shouldn't be necessary but if it is working ....

Just checked your profile and I see you are in Brazil which is UTC-3 - which means the values you are seeing for the getTime() are correct.

What do you get when you dump the now value?

console.log(now);
Eduardo FuerteDeveloper and Analyst

Author

Commented:
This:
1549309222818
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Ok I need to see both Now and the converted timestamp otherwise I can't do a comparison.

Can you do this.
console.log(now);
console.log(fromtime.getTime());

Open in new window

Eduardo FuerteDeveloper and Analyst

Author

Commented:
Here it is:
img001
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Those are only 187 seconds apart?
Eduardo FuerteDeveloper and Analyst

Author

Commented:
I didn't change the textbox value.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Then the < 3 message should show.
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Outstanding assistance!
Thank you.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial