How to format dd/mm/yyyy date to mm/dd/yyyy

Asked

Viewed 2,655 times

2

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 appears saying 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 date in the format (dd/mm/yyyy) in the new date.

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

.

2 answers

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 get more information about the split here.

  • When I try to use this Function appears "data.split is not a Function"

  • Try data.toString().split. Javascript is probably interpreting this variable as another type. It needs to be a String to use this function.

2


You can use a substr simple 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;

https://jsfiddle.net/cggy9zx7/6/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.