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

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
Eduardo FuerteDeveloper and AnalystAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Eduardo FuerteDeveloper and AnalystAuthor Commented:
Hi @Julian

The code runs at front-end.
I'm looking your solution, but the working sample is missed.
Julian HansenCommented:
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
Price Your IT Services for Profit

Managed service contracts are great - when they're making you money. Yes, you’re getting paid monthly, but is it actually profitable? Learn to calculate your hourly overhead burden so you can master your IT services pricing strategy.

Eduardo FuerteDeveloper and AnalystAuthor Commented:
Hi @Julian

The server where the example runs seens not working out today.
Could you give a look?
Eduardo FuerteDeveloper and AnalystAuthor Commented:
Ok. Now.
Eduardo FuerteDeveloper and AnalystAuthor 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.
Julian HansenCommented:
I just tested your code in my sample and it seems to work fine.

You can see it working here
Julian HansenCommented:
.... 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 AnalystAuthor 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 AnalystAuthor 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

Julian HansenCommented:
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 AnalystAuthor 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
Julian HansenCommented:
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 AnalystAuthor 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.
Julian HansenCommented:
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 AnalystAuthor Commented:
This:
1549309222818
Julian HansenCommented:
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 AnalystAuthor Commented:
Here it is:
img001
Julian HansenCommented:
Those are only 187 seconds apart?
Eduardo FuerteDeveloper and AnalystAuthor Commented:
I didn't change the textbox value.
Julian HansenCommented:
Then the < 3 message should show.
Eduardo FuerteDeveloper and AnalystAuthor Commented:
Outstanding assistance!
Thank you.
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.