Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
desea convertir el formato de fecha 24/05/2021 a 24/mayo/2021 al usar jQuery/JavaScript

Tengo una fecha 24/05/2021 , quiero convertir su formato de fecha a 24/May/2021 usando Javascript o jquery cuando el usuario deja el cuadro de textbox , mi cliente no quiere usar el selector de fechas , solo quiere escribir las fechas directamente y convierte automáticamente la fecha cuando sale del cuadro de texto, como lo hace en Excel.

Encontré muchas formas pero no obtuve nada, sé cómo hacerlo del lado del servidor pero tiene que hacerse del lado del cliente.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Como dijo que el cliente no quiere usar el selector de fecha , debe definir el formato que ingresará el usuario.

Puede dividir cada segmento y luego formatear el mes, luego poner el valor en el valor del elemento de input en DOM.

En cuanto al ejemplo a continuación, asumo que el usuario usa / como separador para la entrada.

 function formatDate(val){ var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var parts = val.split('/'); var d = parts[0]; var y = parts[2]; var m = months[parseInt(parts[1], 10) - 1]; var inp = document.querySelector('#inp'); if(/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/.test(val)){ inp.value = `${d}/${m}/${y}`; } else inp.value = ""; }
 <input type="text" id="inp" required pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}" onchange="formatDate(this.value)"/>

about 4 years ago · Juan Pablo Isaza Report

0

puede usar expresiones regulares para verificar si la fecha ingresada es correcta o no, si es correcta, puede cambiar su formato; de lo contrario, puede mostrar un error. Aquí está el código:

 const month = ["January","February","March","April","May","une","July","August","September","October","November","December"]; const dateregex = /^[0-3]?[0-9]\/[0-1]?[0-9]\/[0-9][0-9][0-9][0-9]/ class DateField { constructor(id) { this.elem = document.getElementById(id); this.elemInp = this.elem.children[1]; this.elemError = this.elem.children[0]; this.date = null; this.elemInp.addEventListener('blur', () => { console.log(dateregex.test(this.elemInp.value), dateregex, this.elemInp.value); if (!dateregex.test(this.elemInp.value)) { this.showError(); this.date = null; return; } var datesplits = this.elemInp.value.split('/'); this.date = new Date(); this.date.setYear(parseInt(datesplits[2],10)); this.date.setDate(parseInt(datesplits[0],10)); this.date.setMonth(parseInt(datesplits[1],10) - 1); var newDateString = this.date.getDate() + '/' + month[this.date.getMonth()] + '/' + this.date.getFullYear(); this.elemInp.value = newDateString; this.removeError(); }); this.elemInp.addEventListener('focus', () => { if (this.date !== null && !isNaN(this.date.getTime())) { var newDateString = this.date.getDate() + '/' + (this.date.getMonth() + 1) + '/' + this.date.getFullYear(); this.elemInp.value = newDateString; } }); } showError() { this.elemError.innerText = "date is invalid"; } removeError() { this.elemError.innerText = ""; } } var d1 = new DateField("dateContainer");
 <html> <head> <title>try js</title> </head> <body> <div id="dateContainer"> <p style="color: red;"></p> <input type="text" id="date" /> </div> </body> </html>

about 4 years ago · Juan Pablo Isaza Report

0

Puede dividir la cadena en "/" y luego, con el segundo elemento de la matriz, crea una matriz con los meses como esta:

 const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

Luego divide su cadena en "/" y obtiene una fecha como:

 const split = document.querySelector("#input").split("/"); const date = new Date(`${split[1]}/${split[0]}/${split[2]}`);

Y finalmente:

 const month = monthNames[date.getMonth()];

El HTML va a ser algo como esto:

 <input type="text" id="input" required onchange="formatDate(this.value)"/>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!