Native Javascript date formatting does not work

Asked

Viewed 157 times

1

I have a modal filled via Javascript. The Javascript code is as follows::

// INTERFACE MODAL viewVenda
$(document).ready(function () {
    $(document).on('click', '.view_data', function () {
        var id = $(this).attr("id");
        if (id !== '') {
            var dados = {
                id: id
            };
            $.post('dsVenda.php', dados, function (retorna) {
                var venda = ['', '', '', '', '', '', '', '', '', ''];
                venda = retorna.split(',');
                $("#var0").html(venda[0]);
                $("#var1").html(venda[1]);
                $("#var2").html(venda[2]);
                $("#var3").html(venda[3]);
                $("#var4").html(venda[4]);
                $("#var5").html(venda[5]);
                var data = venda[6];
                data_formatada = data.toLocaleDateString('pt-br');
                $("#var6").html(data_formatada);
                $("#var7").html(venda[7]);
                $("#var8").html(venda[8]);
                $("#var9").html(venda[9]);
                $('#viewVenda').modal('show');
            });
        }
    });
});

The variable contained in sale[6] has the value 2020-03-06 15:11:15 registered in the database.

I am formatting via native Javascript function for the Brazil dd/MM/yyyy standard but the modal does not open. If I show the gross value as follows it opens.

$("#var6").html(venda[6]);

The same problem happens if I try to format sale[3] and sale[5] value which is monetary

  • 1

    Just a detail, if you want to always force the Brazilian format, pass the locale as a parameter: data.toLocaleDateString('pt-BR') - otherwise it will take the locale that is configured in the browser, and it is not always guaranteed that it is pt-BR - ex: https://repl.it/repls/SandyOvercookedAlgorithm - Anyway, where is the modal? It gives an error (and if so, which is the message)? venda[6] is a string in the format "2020-03-06 15:11:15" or is a Date? (you can’t test that code without knowing that information, and maybe is why the question is receiving negative votes)

  • 3

    The mistake is that the toLocaleDateString only works with object Date. Because of the error the script stops running.

  • sale[] is a vector. picked the position [6] of it.

  • Yes, but position 6 has a string, a Date, or what? If he doesn’t have one Date, then the problem is what Sam said above. If he has a Date, then the problem must be elsewhere, etc.. Do you understand how there’s no way we can test and only with the information of the question is the only option is to guess? That could explain the negative votes... Please click [Edit] and enter the necessary information so that anyone can test (I suggest you read how to assemble a [mcve] <<< here are several tips for setting a suitable example)

  • 1

    var data = venda[6]; is a string, you are trying to use the method toLocaleDateString which is the Date object, as @Sam said. You can use "2020-03-06 15:11:15".replace(/(\d{4})\-(\d{2})\-(\d{2})(.*)/, "$3/$2/$1"); in place.

  • @Benilson worked out with the date field. I tried to make a REGEX to use with monetary fields but it did not work, as it would be to format type R $ 32.000,00?

Show 1 more comment

1 answer

1


Maybe this will help you:

var data = new Date();
data.toLocaleDateString('pt-br');
var hora = data.getHours();
var minuto = data.getMinutes();
var segundos = data.getSeconds();
var dia = data.getDate();
var mes = data.getMonth() + 1;
var ano = data.getFullYear();

console.log(`Hoje é exatamente ${dia}/${mes}/${ano}`)
console.log(`São exatamente: ${hora}:${minuto}:${segundos}`)

Another alternative is to use momenjs:

run the command: npm install moment at the command prompt and inside the project directory

and then configure the file like this:

const moment = require('moment');

moment(/*se tiver variável de data passe aqui*/).locale('pt-br').format('DD/MM/YYYY')
  • What to call toLocaleDateString if you don’t use her return for anything? Another detail is that toLocaleDateString('pt-BR') returns the values with zero to the left if necessary (ex: 17/03/2020) and its code does not treat this (returns 17/3/2020). Anyway, the question doesn’t seem to be exactly "how to format date" and yes "modal does not open when I use this code" (although it was not clear which modal this is and which error occurs, but in which way, the problem seems to have relation with this modal, and not with the formatting itself)

  • Friend just answered what’s in the question of the title, so the question has to be improved, and thanks for the tip

  • What must be answered is the problem being described in the body of the question. If the question is not clear and/or does not correspond to the title, then it is best to ask the author for clarification and only answer after he improves the question.

Browser other questions tagged

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