Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
My input date is in dd-mm-yyyy but for some reason the newDate function is changing it to mm-dd-yy in React js

This is my code which is validating the input and in dd-mm-yyyy but the show day function is changing it to mm-dd-yyyy and thus giving me wrong day. i have used console to check the output and if you want to see the code running https://jsfiddle.net/tjpvhwsc/1/ please input 12/01/1994 the output should be 12/01/1994 but it is showing 01/12/1994

  function isValidDate(inputDate){
        if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(inputDate))
        return false; 
        var parts = inputDate.split("/");//12 01 1994
        var day = parseInt(parts[0], 10);
        var month = parseInt(parts[1], 10);
        var year = parseInt(parts[2], 10);
        if(year < 1000 || year > 3000 || month == 0 || month > 12)return false;
        var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
            monthLength[1] = 29;
        
        return day > 0 && day <= monthLength[month - 1];
        
    }

class Inputdate extends React.Component {
       state={
           inputDate:'',
           day:''
       }
       
     showDay=(inputDate)=>{
         console.log(inputDate)
        var d = inputDate.split("/\D/");
        console.log("REceived date", d)
        let dt = new Date(d).toLocaleString('en-GB')
        console.log("new date", dt);
        // const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
        // const weekday = dt.toLocaleString('en-GB')
        // console.log("Formatted date", weekday);
        // this.setState({day:weekday})
        
     } 
   render() {
          console.log(this.state)
        return (
          <div>
            <input
                name="date"
              type="text"
              value={this.state.value}
              placeholder="dd/mm/yyyy"
              onChange={(e)=> {
                 if(isValidDate(e.target.value)){
                    this.setState({inputDate : e.target.value})
                 }
                 else{
                    this.setState({inputDate : 'invalid date'})
                 }
              }}
            />
            <p>{this.state.inputDate}</p>
            <div onClick={()=>this.showDay(this.state.inputDate)}>Show Day</div>
          </div>
        );
      }
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use type="Date" and e.target.value will be formatted according to ISO-8601. For 12th January 1994 you will get 1994-01-12 which will be consistently parsed by new Date().

Or you could go 1 better and use e.target.valueAsDate and get an actual Date object representing the inputted date.

With type="date" the onchange handler will only be triggered for a valid date too.

function parseDate(){
  const date = document.getElementById('date').valueAsDate;
  
  console.log(date);
  console.log(date.toLocaleDateString('en-GB'));
}
<input type="date" onchange="parseDate()" id="date">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda