Date 01 day of the month returns as last

Asked

Viewed 442 times

3

When I enter day 01 as date, it returns to me the last day of the previous month. What is the reason?

	function myFunction() {
		var fromdate = new Date(document.getElementById('data_venc').value);
		alert(fromdate);
        var dd = fromdate.getDate();
        var mm = fromdate.getMonth()+1; //January is 0!
        var yyyy = fromdate.getFullYear();
		alert(dd + " " + mm);
        if(dd < 10)
        {
            dd = '0'+ dd;
			alert(dd);
        }
        if(mm < 10)
        {
            mm = '0' + mm;
			alert(mm);
        }
       //alert(newdate1);
	}
<html>
	</head>
	</head>
	<body>
		<div class="recuperar_usuario_senha">
			<form>
				<h2> Digite a data de vencimento: </h2>
				<input type="date" name="data_venc" id="data_venc"/>
				<h2>Informações Adicionais</h2>
				<textarea cols="45" rows="8" name="textarea" id="textarea" maxlength="225"></textarea>
				</br><input onClick="myFunction()" type="image" src="img/gera_boleto.png" value="Confirmar" id="gera_boleto">
			</form>
		</div>
 	</body>
</html>

3 answers

3

This is because javascript is converting the date to the current time zone. See that the end of the first alert ends with GMT-0300:

Wed Dec 31 2014 21:00:00 GMT-0300 (Hora oficial do Brasil)

That is, the calculated result is 01/01/2015 - 3h.

To solve this problem, use the method toGMTString():

var input = document.getElementById('date').valueAsDate;
console.log(input.toGMTString()); // Thu, 01 Jan 2015 00:00:00 GMT

2

I did not find a reference for this bug, but apparently it is performing a subtraction, because the format passed is YYYY-MM-DD, concatenating with a string " " the date is converted correctly.

You can use the toLocaleDateString("pt-BR") to format in the Brazilian DD/MM/AAAA as an example below.

function myFunction() {
  var fromdate = new Date(document.getElementById('data_venc').value + " ");
  alert(fromdate);
  var dd = fromdate.getDate();
  var mm = fromdate.getMonth() + 1; //January is 0!
  var yyyy = fromdate.getFullYear();
  alert(dd + " " + mm);
  if (dd < 10) {
    dd = '0' + dd;
    alert(dd);
  }
  if (mm < 10) {
    mm = '0' + mm;
    alert(mm);
  }
  var r = fromdate.toLocaleDateString("pt-BR")
  alert(r);
}
<html>
</head>
</head>

<body>
  <div class="recuperar_usuario_senha">
    <form>
      <h2> Digite a data de vencimento: </h2>
      <input type="date" name="data_venc" id="data_venc" />
      <h2>Informações Adicionais</h2>
      <textarea cols="45" rows="8" name="textarea" id="textarea" maxlength="225"></textarea>
      </br>
      <input onClick="myFunction()" type="image" src="img/gera_boleto.png" value="Confirmar" id="gera_boleto">
    </form>
  </div>
</body>

</html>

0

I ended up changing the project a little. The two answers worked perfectly, but since I need to compare two dates, I ended up changing the project a little and using the dates in the original format. To resolve this, I added a day in the date before the conversion to seconds. Follow the code:

function myFunction() {
			var valorBoleto = document.getElementById('valor').value; // joga o valor na variavel valorBoleto
			var dataBoletoString = document.getElementById('data_venc').value; // joga a data na variavel dataBoletoString
			var dataBoleto = new Date(dataBoletoString);
			dataBoleto.setDate(dataBoleto.getDate() + 1);
			var dataBoletoSegundos = dataBoleto.getTime();
			var dataHoje = new Date();
			var dataHojeSegundos = dataHoje.getTime();
			if (valorBoleto <= 0){
				alert("Valor inválido! Insira o valor do boleto.");
			}else{
				var res = window.confirm("O valor do boleto é: R$ "+ valorBoleto + ". Está correto?");
				if (res == true){
					if(dataBoletoSegundos >= dataHojeSegundos){
						var dataCorreta = confirm("O vencimento deste boleto é dia: "+ dataBoleto.toLocaleDateString("pt-BR") + " , está correto?")
						if(dataCorreta == true){
							location.href="escolher_estab.php";
							window.open("boleto_manual.php", "_blank", "toolbar=yes, scrollbar=yes, resizable=yes, top=500, left=500, width=500, height=400");
						}
					}else{
						alert("O sistema não aceita datas anteriores ao dia de hoje.");
					}
				}
			}
		}
<body oncontextmenu='return false' onselectstart='return false' ondragstart='return false'>  <!-- Não deixa o usuário clicar com o botão direito na página -->
		<div class="container clearfix">
			<?php
				include "header.php";
			?>
			<div class="recuperar_usuario_senha">
				<form method="post" action="?acao=confirmar">
					<h1>Enviar boleto <em>SICLOP</em></h1>
					<h2> para <?php echo $nome_estab?></h2>
					<input type="password" name="estab" id="estab" value="<?php echo $nome_estab ?>" style="display:none"/> <!-- Nome do estabelecimento invisível para o usuário, para podermos pegar depois na ação GET -->
					<h2>Digite o valor do boleto:</h2>
					<input type="text" name="valor" id="valor"/>
					<h2> Digite a data de vencimento: </h2>
					<input type="date" name="data_venc" id="data_venc"/>
					<h2>Informações Adicionais</h2>
					<textarea cols="45" rows="8" name="textarea" id="textarea" maxlength="225"></textarea>
					</br><input onClick="myFunction()" type="image" src="img/gera_boleto.png" value="Confirmar" id="gera_boleto">
				</form>
			</div>
			<?php
				include "footer.php";
			?>
		</div>
 	</body>

Browser other questions tagged

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