How to format dd / mm / yyyy for mm / dd / yyyy

1

I'm getting this date in a variable:

var data = "23/03/2012 00:00:00"

I need to put this date in an input type date. When I try, the message says that I need to pass through the format (yyyy-mm-dd)

I found this function that formats date:

function formatarData(data) {

            var d = new Date(data),
                mes = '' + (d.getMonth() + 1),
                dia = '' + d.getDate(),
                ano = d.getFullYear();

            if (mes.length < 2) mes = '0' + mes;
            if (dia.length < 2) dia = '0' + dia;

            return [ano, mes, dia].join('-');
        }

However, when I try to execute the function with the date I'm receiving, it returns (NaN-NaN-NaN).

I searched here on the internet, and saw that you can not pass date in the format (dd / mm / yyyy) in new Date.

Then I need to format my date dd / mm / yyyy to mm / dd / yyyy. Could someone help me?

.

    
asked by anonymous 28.03.2018 / 19:43

2 answers

2

You can use a simple substr as shown below.

var data = "23/03/2012 00:00:00",
    dateBlock = data.substr(6,4)+"-"+data.substr(3,2)+"-"+data.substr(0,2),
    hourBlock=data.substr(11),
    dateObj=new Date(dateBlock+" "+hourBlock);

document.body.innerHTML = "Objeto Data: "+dateObj;
document.body.innerHTML += "<br>Data: "+dateBlock;
document.body.innerHTML += "<br>Hora: "+hourBlock;

link

    
28.03.2018 / 20:16
2

Following this date pattern, you can use:

function formatarData(data) {

    // da "split" no 'espaço'
    var d = data.split(" ")[0]; // recupera 23/03/2012
    var h = data.split(" ")[1]; // recupera 00:00:00

    var dsplit = d.split("/"); // recupera o array(23, 03, 2012);
    var hsplit = h.split(":"); // recupera o array(00, 00, 00);

    // cria o objeto date
    var novaData = new Date(dsplit[2], dsplit[1] - 1, dsplit[0], hsplit[0], hsplit[1], hsplit[2]);

    // retorna o objeto date
    return novaData;

}

You can learn more about here .

    
28.03.2018 / 19:59