Format date javascript

1

I have the following string:

var fecha = "10-ene-2000";

I would like to format it in the following way but still be a string:

var result = "2000-01-10 00:00:00"

How can I do it automatically?

    
asked by sirdaiz 29.08.2017 в 11:18
source

2 answers

3

For this you will first have to collect the date in format (YYYY-MM-DDTHH: MM: SSZ). Then convert it to string. Where does the date come from? How are you picking it up?

It does not help at all to format "10-Jan-2000" (string) to "2000-01-10 00:00:00" (string), since a string does not contain the hour / minutes / seconds.

I leave a link to W3C in step: Date Formats

Why do I understand that you want the hour / minutes / seconds to be correct right?

EDIT: Edit according to comment:

//Convertir el string a fecha para poder modificarlo
Date.parse(fecha);
//Poner el formato que quieres
dateFormat(fecha, "yyyy, mm, dd h:MM:ss");
//Volver a convertirlo a string
fecha.toString();
    
answered by 29.08.2017 / 11:23
source
1

If the issue of not having accuracy with the time, minutes and seconds gives you the same (ie, that a string is generated with 00:00:00) I think this solution can be worth it.

The first thing is to map the strings of the months as numbers (same as there is a function that does it, but since I do not know it I recommend this method that is more flexible).

function convertirFecha(fecha){
    //Objeto javascript que vamos a utilizar como tabla hash para
    //La conversion de los meses a su representacion numerica

    let conversorMeses = {
        'ene' : '01',
        'feb' : '02',
        (...),
        'dic' : '12'
    };

    //Obtenemos el dia mes y año de la fecha original
    //Tal y como has puesto:
    //paramFecha[0] -> dia
    //paramFecha[1] -> mes
    //paramFecha[2] -> año

    let paramFecha = fecha.split("-");

    //Una vez tenemos los datos montamos el string resultante 
    let fechaRes = paramFecha[2] + "-" + conversorMeses[paramFecha[1]] + "-" + paramFecha[0] + " 00:00:00";

    return fechaRes;

}
    
answered by 29.08.2017 в 11:32