Date 01 day of month returns as last

3

When I enter day 01 as the date, it returns 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>
    
asked by anonymous 10.07.2015 / 22:55

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 calculation performed is 01/01/2015 - 3h .

To work around this problem, use the toGMTString () :

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

I have not found a reference to this bug, but apparently it is doing a subtraction, since the last format is YYYY-MM-DD, concatenating with a string " " , the date is converted correctly.

You can use toLocaleDateString("pt-BR") to format in the Brazilian standard of DD/MM/AAAA as shown 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>
    
10.07.2015 / 23:20
0

I ended up changing the project a bit. The two answers worked perfectly, but as I need to compare two dates, I ended up changing the project a bit and using the dates in the original format. To resolve this, I added a date day before the conversion to seconds. Here is 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>
    
13.07.2015 / 21:09