Convert a date in format 1-Jan-2017 to 01-01-2017 format

0

I am trying to convert a date with the format 1-Ene-2017 and successively with every month, to the format 01-01-2017 .

I get this date from a field called hidFechaFinal with the following code:

function validaFechasAsignacion(){
    var fecha_f = document.getElementById("hidFechaFinal").value;

    if(typeof fecha_f === 'undefined' || fecha_f == null || fecha_f == ""){
        alert("Seleccione la fecha final.");
        return false;
    }

    var fechaFinal = new Date(fecha_f); //AQUI HAGO LA CONVERSION DE LA FECHA
    alert("Fecha Final: " + fechaFinal); //AQUI IMPRIME InvalidDate
}

When I execute this function the alert shows the message:

  

Final Date: InvalidDate

I suspect it's because the month is abbreviated in Spanish.

    
asked by TimeToCode 29.11.2017 в 19:34
source

1 answer

1

When working with dates I use the library momentjs .

A solution to your problem using momentjs could be as follows:

function validaFechasAsignacion(){
    var fecha_f = document.getElementById("hidFechaFinal").value;

    // Formato 1-Ene-2017
    var fecha = moment(fecha_f, 'D-MMM-YYYY', true);
    if(!fecha.isValid()){
        alert("Seleccione la fecha final.");
        return false;
    }

    alert("Fecha Final: " + fecha.format('DD-MM-YYYY'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/locale/es.js"></script>
<input type="text" id="hidFechaFinal" placeholder="Ej: 1-Ene-2017"/>
<br>
<br>
<button type="button" onclick="validaFechasAsignacion()">Validar</button>
    
answered by 29.11.2017 / 20:00
source