Convert string to Date (dd-mm-yyyy)

0

Hello, I need some help.

I have a string="01/04/2012" and need to convert to date (dd-mm-yyyy) in pure javascript.

Here's what I did:

var vencimento = localStorage.getItem('dados2'); //Busca a variável que contém a string = 01/04/2012
var vencimento2 = new Date(vencimento); // = Wed Jan 04 2012 00:00:00 GMT-0200 (Horário brasileiro de verão)
var vencimento3 = ???

How could I turn that date into DD-MM-YYYY? I just found examples in jQuery: /

    
asked by anonymous 13.03.2018 / 17:34

2 answers

3

You can do the following function:

function toDate(dateStr) {
    var parts = dateStr.split("/");
    return new Date(parts[2], parts[1] - 1, parts[0]);
}

Any questions or additional suggestions follow the link .

    
13.03.2018 / 17:44
3

You can "explode" the values by separating them with the slash.

For example:

/* Separa os valores */
let dataString = "01/04/2012".split("/");

/* Define a data com os valores separados */
let data = new Date(dataString[2], dataString[1]-1, dataString[0]);

console.log( data.toString() );
console.log( data.toLocaleDateString("pt-BR") );
    
13.03.2018 / 17:36