Format database date for javascript

Asked

Viewed 105 times

0

I am mounting a table on the datatables with date and time information. But the data comes in the database in YYYY-mm-dd default. How do I change and show in datatable as dd/mm/YYYY?

My code:

function retornarColetas(data) {
            var coletas = "";
                            
            $.each(data, function (chave, valor) {
                coletas += '<tr>' +
                        '<td>' + valor.id_coleta + '</td>' +
                        '<td>' + valor.cliente + '</td>' +
                        '<td>' + valor.data + '</td>' +
                        '<td>' + valor.hora + '</td>' +
                        '<td>' + valor.vendedor + '</td>' +
                        '<td>' + valor.status + '</td>' +
                        '<td>' +
                        '<a class="btn btn-sm btn-outline-info text-info mr-2"><i class="fas fa-pencil-alt"></i> Editar</a>' +
                        '<a class="btn btn-sm btn-outline-danger text-danger"><i class="far fa-trash-alt"></i> Excluir</a>' +
                        '</td>';
            });
            $('#tabelaColeta').html(coletas);

        }

1 answer

1


Assuming that your data come in this format: 2020-10-20, Voce can make (in a very direct way) a split(), soon after a reverse()(see here), and finally do join().

Would look like this:

const data = '2020-10-20'.split('-').reverse().join('/');

console.log(data);

What happens:

  • You separate the string in a array with the split(): ['2020', '10', '20'];
  • You reverse the array with reverse(): ['20','10','2020'];
  • And makes a join() using the /: 20/10/2020

Your code would look like this:

 $.each(data, function (chave, valor) {
                var dataFormatada = valor.data.split('-').reverse().join('/');

                coletas += '<tr>' +
                        '<td>' + valor.id_coleta + '</td>' +
                        '<td>' + valor.cliente + '</td>' +
                        '<td>' + dataFormatada + '</td>' +
                        '<td>' + valor.hora + '</td>' +
                        '<td>' + valor.vendedor + '</td>' +
                        '<td>' + valor.status + '</td>' +
                        '<td>' +
                        '<a class="btn btn-sm btn-outline-info text-info mr-2"><i class="fas fa-pencil-alt"></i> Editar</a>' +
                        '<a class="btn btn-sm btn-outline-danger text-danger"><i class="far fa-trash-alt"></i> Excluir</a>' +
                        '</td>';
            });
            $('#tabelaColeta').html(coletas);
  • Perfect. Thank you so much for your help! Note 10!

Browser other questions tagged

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