Convert string to Date (dd-mm-yyyy)

Asked

Viewed 9,287 times

4

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

Follow what I’ve done:

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 only found examples in jQuery.

3 answers

10


You can do the following function:

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

Any further doubt or suggestion follows the link.

8

You can "explode" the values by separating them by the bar.

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") );

  • Dude, but there’s no date. I did here it returns the date with string dnv, the same way I pull it

  • When you assign new Date(dataString[2], dataString[1]-1, dataString[0]);, you already have the format Date, including adding, subtracting, changing values.

1

I know it’s been a while since that question was answered, but for the record, we have another option.

function toDateISO(dateStr) {
    return dateStr.split('/').reverse().join('-');
}

toDateISO('30/12/2021'); // 2021-12-30

It is possible to convert to Date, if so wish, just put new Date().

function toDate(dateStr) {
    return new Date(dateStr.split('/').reverse().join('-') + ' 00:00:00');
}

toDateISO('30/12/2021'); // Thu Dec 30 2021 00:00:00 GMT-0300 (Horário Padrão de Brasília)

Without the time the response will be different, as can be observed below.

function toDate(dateStr) {
    return new Date(dateStr.split('/').reverse().join('-'));
}

toDateISO('30/12/2021'); // Thu Dec 29 2021 21:00:00 GMT-0300 (Horário Padrão de Brasília)

Browser other questions tagged

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