javascript date format how to change date format?

0

Good I have problems with the format of dates my code is the following

fecha = new Date();
    entrega = new Date();
    dia = fecha.getDate();
    mes = fecha.getMonth()+1;// +1 porque los meses empiezan en 0
    anio = fecha.getFullYear();
  entrega.setMonth(entrega.getMonth() + 4);

var d = new Date();
var strDate = d.getFullYear() + "-0" + (d.getMonth()+1) + "-0" + d.getDate();


    var mesMax="-0"+entrega.getMonth();
    console.log(mesMax);
    var fechaMas = d.getFullYear()+mesMax+"-0"+d.getDate();
    console.log(fechaMas);

    console.log($('#fei').val());
   console.log('fecha compara si es menor');
   console.log(strDate);
     if($('#fei').val()>fechaMas)
     {
      swal('ERROR!','La fecha seleccionada es mayor a 3 meses','error').then($('#fei').val(strDate));

     }else if($('#fei').val()<strDate){
      swal('ERROR!','La fecha seleccionada es menor a la actual','error').then($('#fei').val(strDate));
     }else{console.log('no es mayor');}

It's fine and everything but the problem is that for example today is the 4th of January and it prints 4 I want it to be 04, so for the month this month is 01 and it prints me 1, that's why in the code I have to add the 0 before, how could that be resolved so as not to be changing so that I already have it, at the time of validation I get problems so I take the format, some advice?

ok I could just put a validation

if((d.getMonth()+1)<=9){cero = "-0"+(d.getMonth()+1)}else{cero=(d.getMonth()+1)}

and with that I solve the rest

    
asked by Juan Jose 04.01.2019 в 22:18
source

2 answers

0

I use a function that returns the numbers with that format for the months and days.

limpiarNumero( n: number ) {
  return n < 10 ? '0${n}' : n.toString();
}

let ddia = limpiarNumero(5); // 05
let mmes = limpiarNumero(15); // 15
    
answered by 05.01.2019 в 00:12
0

I recommend the Moment JS library, it will help you a lot with the management of dates and times, in javascript sometimes the management of these is complicated data types.

Import the library (CDN) or download the library and import it from the local directory     

To get the current date you do it using moment() , to format it you can do it in this way moment.format ('YYYY-MM-DD') or else moment.format ('YYYYMMDD') if you need it if scripts .

And finally to get the month and the day as you need it, you do it this way (for the current day)

let dia = moment().format('DD')
let mes = moment().format('MM')

If you need to pass a date that you need to get its value in day and month you do it this way:

let miFecha = new Date()
console.log(moment(miFecha).format('DD'))
console.log(moment(miFecha).format('MM'))

Greetings,

    
answered by 05.01.2019 в 00:31