How to check dates in input datetime?

Asked

Viewed 403 times

2

I have an HTML page with an input date/time and date/time out form (input datetime-local).

I need to check on the same page if the fields were filled only with different dates at the time the user clicks the button submit.

function validar() {
var dataHoraInicio = formInsere.dataHoraInicio.value;
var dataHoraFim    = formInsere.dataHoraFim.value;

if (dataHoraInicio == "") {
alert('Preencha o campo data hora entrada!');
formInsere.dataHoraInicio.focus();
return false;
}

if (dataHoraFim == "") {
alert('Preencha o campo data hora saida!');
formInsere.dataHoraInicio.focus();
return false;
}

}//fim function//
<html>
<head>
</head>
<body>

<br>
<br>

<form id="formInsere" action="valida.php" name="formInsere" method="POST" >
             
			 <label>&nbsp;Data hor&aacute;rio entrada<br>
            <input type="datetime-local" name="dataHoraInicio">
        </label>
        <br><br>
                <label>&nbsp;Data hor&aacute;rio sa&iacute;da<br>
                    <input type="datetime-local" name="dataHoraFim">
                </label><br>
                <br><br>
				
		<input type="submit"  onclick="return validar()">		
</form>



</body>
</html> 

1 answer

1

The first thing is to understand that the value of a field datetime-local is a string in format ISO 8601. Example:

function validar(evt) {
  let dataHoraInicio = document.querySelector('#formInsere').dataHoraInicio.value;
  console.log(dataHoraInicio);
  console.log(typeof dataHoraInicio); // string
  evt.preventDefault();
}

document.querySelector('#formInsere').addEventListener('submit', validar);
<form id="formInsere" name="formInsere" method="POST" >
  <input type="datetime-local" name="dataHoraInicio">
  <input type="submit">     
</form>

Placing the date "15 March 2019 at 10:30 am", the variable dataHoraInicio shall be equal to 2019-03-15T10:30. Any date you place will have your value in that format ("yyyy-mm-ddThh:mm").

Fortunately the class Date javascript recognizes this format, then you just pass this value to the builder, and then check if the day, month and year are the same.

From what I understand, the form should not be submitted if the date (day, month and year) is equal, regardless of the chosen times. So just compare the day, month and year:

let formulario = document.querySelector('#formInsere');

function validar(evt) {
  let dataHoraInicio = formulario.dataHoraInicio.value;
  let dataHoraFim    = formulario.dataHoraFim.value;
  if (dataHoraInicio == "") {
    alert('Preencha o campo data hora entrada!');
    formulario.dataHoraInicio.focus();
    evt.preventDefault();
  } else if (dataHoraFim == "") {
    alert('Preencha o campo data hora saida!');
    formulario.dataHoraInicio.focus();
    evt.preventDefault();
  } else {
    // cria as datas
    let dtInicio = new Date(dataHoraInicio);
    let dtFim = new Date(dataHoraFim);
    // verifica se o dia, mês e ano são iguais
    if (dtInicio.getDate() === dtFim.getDate()
        && dtInicio.getMonth() === dtFim.getMonth()
        && dtInicio.getFullYear() === dtFim.getFullYear()) {
      alert('As datas não podem estar no mesmo dia');
      evt.preventDefault();
    }
  }
}

formulario.addEventListener('submit', validar);
<form id="formInsere" name="formInsere" method="POST">
    <label>&nbsp;Data hor&aacute;rio entrada</label>
    <input type="datetime-local" name="dataHoraInicio"><br>
    <label>&nbsp;Data hor&aacute;rio sa&iacute;da</label>
    <input type="datetime-local" name="dataHoraFim"><br>
    <input type="submit">
</form>

The above comparison considers only the day (getDate()), month (getMonth()) and year (getFullYear()). Note not to misuse methods getDay() (which returns the day of the week, not the day of the month) and getYear() (that besides being deprecated, returns the year indexed in 1900 - i.e., 2019 is returned as 119).

If you want to compare both date and time, just change the if for:

if (dtInicio.getTime() === dtFim.getTime()) {
    // datas são iguais (tanto o dia/mês/ano quanto o horário)
}

getTime() returns the value of timestamp (the number of milliseconds since the Unix Epoch), and is the most direct way to check that the dates match exactly the same instant.


Remembering that some browsers can’t stand it the input type=datetime-local, but the documentation describes ways to circumvent this limitation.

  • Ok, I’m aware that some browsers do not support!

  • Thank you so much for your help!

  • @Phelipemachado If the answer solved your problem, you can choose to accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points you can also vote in all the answers you found useful.

  • Friend, in case the dates are not different, ex: start date 04-04-2019 07:00 end time 04-04-2019 17:00 what would be the validation? Because I changed the operator === to != and it didn’t work! Could you help me, please!?

  • I suggest you edit the question and enter the code, as this makes it easier to discover the problem

  • @Phelipemachado It should work at first. If you’re doing === and changed to !==, no reason to make a mistake. That’s why I suggested that edit the question and put the code, because only with "did not work" can not know what is wrong

Show 1 more comment

Browser other questions tagged

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