1

Good morning, as quoted above, I need to convert the date YYYY-MM-DD to DD-MM-YYYY so that only the date appears and not the time respectively in all tags with the same class but with different dates.

I used the each to pass in each class and enter the values within an array, to store only the date, I used the split, but at the time to use the for, did not work, probably way of constructing the code is wrong.

<p class="data">2019-10-30 10:20:10</p>
<p class="data">2018-01-20 10:20:10</p>
<p class="data">2012-03-10 10:20:10</p>

<script>
    window.onload = function() {
        var data = [];

        $(".data").each(function() {
            data.push($(this).html().split(" ")[0].split("-"));
        });
        console.log(data)

        for (i = 0; i < data.lenght; i++) {
            $(".data").html(data[i]);
            console.log("test");
        }
    }
</script>

igor rocha
  • 13
  • 2

1 Answers1

1

When dealing with date formats, always convert to a Date object, then output the format required from the various methods of that object. Hacking around a string is very brittle and just asking for a headache.

With that in mind you can use jQuery's text() method to execute a function on each of your .data elements and return the date in the format you require, like this:

$(function() {
  $('p.data').text(function(i, t) {
    var d = new Date(t);
    return ('00' + d.getDate()).slice(-2) + '/' + ('00' + (d.getMonth() + 1)).slice(-2) + '/' + d.getFullYear();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="data">2019-10-30 10:20:10</p>
<p class="data">2018-01-20 10:20:10</p>
<p class="data">2012-03-10 10:20:10</p>
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303