Estoy tratando de obtener la fecha actual para poder usarla al final de este enlace. Mi código es casi correcto, pero no puedo entender qué es lo que va mal.
Mis resultados son casi correctos pero el código regresa con la siguiente fecha 01/0/2022 en lugar de 09/01/2022
¿Puede alguien ayudarme a resolver este pequeño error?
<script> const getDate = () => { let newDate = new Date(); let year = newDate.getFullYear(); let month = newDate.getMonth() + 1; let d = newDate.getDay(); return month + '/' + d + '/' + year; } document.getElementById('Ao').src = 'http://zumdb-prod.itg.com/zum/AppServlet?action=aotool&jspURL=clusterTools/toolset.jsp&fegoaltype=RAW&eedbListName=ZUM_CMP_DNS_CMP_Clean&facility=DMOS5-CLUSTER&monthDate=' .concat(getDate()); document.getElementById('MTD').src = 'http://zumdb-prod.itg.com/zum/AppServlet?action=aotoolFe&jspURL=clusterTools/toolsetFe.jsp&fegoaltype=RAW&eedbListName=ZUM_DIFF_TEL_IPD_HTO&facility=DMOS5-CLUSTER&monthDate=' .concat(getDate()); </script>Debería usar getDate() y no getDay() . Este último devuelve el día de la semana basado en cero (a partir del domingo). Desea obtener la fecha del mes.
Para asegurarse de obtener dos dígitos para el mes y el día, primero debe convertir esos números en cadenas y luego usar String.prototype.padStart .
const getDate = () => { const newDate = new Date(); const year = newDate.getFullYear(); const month = newDate.getMonth() + 1; const d = newDate.getDate(); return `${month.toString().padStart(2, '0')}/${d.toString().padStart(2, '0')}/${year}`; } console.log(getDate());Aquí hay métodos alternativos para el formato de fecha nativo usando toLocaleString()
m/d/aaaa
const getDate = () => { const date = new Date(); return date.toLocaleString().split(",")[0]; } console.log(getDate());mm/dd/aaaa
const getDate = () => { const date = new Date(); return date.toLocaleString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' }); } console.log(getDate());