How to get a date in DD-MM-YYYY format with Javascript?

Question:

I have the following code that adds the days entered in the input and shows them but the date is shown by DD-M-YYYY so when saving it in sql it sends me an error.

  <input type="text" id="fechaImagen" onclick="calculoImagen();" >
  <input type="number" id="frecuenciaDias" value="90" onclick="vaciarFechaSiguiente();" onchange="calculoImagen();" >
  <input type="text" id="siguienteImagen">
<script type="text/javascript">
var f = new Date();
fecha = f.getDate() + "/" + (f.getMonth() +1) + "/" + f.getFullYear();
document.getElementById('fechaImagen').value = fecha;
function calculoImagen() {
    tiempo = document.getElementById('frecuenciaDias').value;
    addTime = tiempo * 86400; //Tiempo en segundos
    f.setSeconds(addTime); //Añado el tiempo
    fechaSiguienteImagen = f.getDate() + "/" + (f.getMonth() + 1) + "/" + f.getFullYear();
    document.getElementById('siguienteImagen').value = fechaSiguienteImagen;
};
function vaciarFechaSiguiente() {
  document.getElementById('siguienteImagen').reset();
}
</script>

How could I set the date to show it in this format DD-MM-YYYY?

Answer:

I tell you that you can achieve it in the following way

let date = new Date()

let day = date.getDate()
let month = date.getMonth() + 1
let year = date.getFullYear()

if(month < 10){
  console.log(`${day}-0${month}-${year}`)
}else{
  console.log(`${day}-${month}-${year}`)
}

Where you can notice the following:

  1. To get the exact day I use getDate() .
  2. To obtain the exact month I add a 1 to the end because they are in the form of an arrangement and January begins in position 0
  3. To add a 0 to the left to month and make it look like you ask, I just put it in an if / else and compared its length
Scroll to Top