How to respect the format dd / mm / yyyy?

0

I want to store a date to which certain days were added, with the function setDate() , Example: 28/02/2018 + 1 day = 01/3/2018 .

So add a if and add the 0 but at the time of storing it does not work

fecha_termino.setDate(fecha_termino.getDate() + diasNum);
             //alert(fechaDate.getDate() + '/' + (fechaDate.getMonth() + 1) + '/' + fechaDate.getFullYear());
   if((fecha_termino.getMonth() + 0) < 10)
    {
      $('#TFecha_termino').val(fecha_termino.getDate() + '/' + '0' +(fecha_termino.getMonth() + 1) + '/' + fecha_termino.getFullYear());
    }
   else
    {
       $('#TFecha_termino').val(fecha_termino.getDate() + '/' + (fecha_termino.getMonth() + 1) + '/' + fecha_termino.getFullYear());
    }   
    
asked by David Melo 01.03.2018 в 05:46
source

1 answer

1

So that the date respects the format dd/mm/yyyy , what is it that I understand that you want to do, not only should you check the month but also the day to know when to add the 0 to the left since currently it is only for the month, so when you change to 01 of March only shows the day 1 .

Ejm

var  fecha_termino = new Date(2018,1,28)
var diasMas= 1;
//Incrementamos la fecha
fecha_termino.setDate(fecha_termino.getDate() + diasMas);

let dia = fecha_termino.getDate();
let mes = fecha_termino.getMonth()+1;

//Si el día es menor a 10 , agregamos el 0
if(dia<10)  dia='0'+dia; 
//Si el mes es menor a 10 , agregamos el 0
if(mes<10)   mes='0'+mes;

//asignamos concatenando los valores
document.getElementById('TFecha_termino').value  = dia+ "/"+ mes + "/" + fecha_termino.getFullYear() ;

//Jquery

//$('#TFecha_termino').val(dia+ "/"+ mes + "/" + fecha_termino.getFullYear());
<input type="text" id="TFecha_termino">

Another slightly more rudimentary way is to use some methods of the arrays, such as slice to extract the entire date, then split to separate the string by the - , reverse to place the day at the beginning and the year at the end, and join to concatenate the result.

var  fecha_termino = new Date(2018,1,28)
var diasNum = 1;
fecha_termino.setDate(fecha_termino.getDate() + diasNum);
$('#TFecha_termino').val(fecha_termino.toJSON().slice(0,10).split('-').reverse().join ('/'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="TFecha_termino">
    
answered by 01.03.2018 / 07:01
source