Sort Divs by date in dd/mm/yyyy format

Asked

Viewed 745 times

2

Does anyone know how I can sort a set of Ivs through a date present in their content?

for example:

<div class="box" id="box1">
    <div class="date">01/05/2018</div>
</div>

<div class="box" id="box2">
    <div class="date">04/05/2018</div>
</div>

<div class="box" id="box3">
    <div class="date">08/05/2018</div>
</div>

<script>
$(document).ready(function(){

$(".box").each(function(){

        var date_content = $(this).find(".date").html();

        //aqui seria o momento de adicionar um codigo para ordena-los.. 
        //preciso que apareça da data maior até a menor.. ou seja, o primeiro box com a data mais recente, e os seguintes com as datas mais antigas... 

    });//end each

});//end doc
</script>
  • but they are already ordered

  • 1

    I need it to appear from the largest date to the smallest.. I mean, the first box with the most recent date, and the following with the oldest dates...

  • The sort I refer to is with respect to the date it contains in html, for example, to look as I would like, starting with the latest date and following to the oldest, would be #box3, #box2, #box1

4 answers

4

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="date-list">
  <div class="box" id="box1">
      <div class="date">01/05/2018</div>
  </div>

  <div class="box" id="box2">
      <div class="date">30/05/2018</div>
  </div>

  <div class="box" id="box3">
      <div class="date">08/05/2018</div>
  </div>
  
  <div class="box" id="box3">
      <div class="date">15/11/2001</div>
  </div>
  
    <div class="box" id="box3">
      <div class="date">08/05/1998</div>
  </div>
</div>
<script>
$(document).ready(function(){
    var dates = [] //Criando um array de datas
    $(".box").each(function(){
        dates.push($(this).find(".date").html());
    });
    
    // Convertendo dd/MM/yyyy para yyyyMMdd
    function dateToNum(d) {
      d = d.split("/");
      console.log(Number(d[2]+d[1]+d[0]));
      return Number(d[2]+d[1]+d[0]);
    }
    
    //Ordenando através da função sort(> para ordem decrescente, < para ordem crescente)
    dates.sort(function(a,b){
      return dateToNum(a) < dateToNum(b);
    });
    
    //Popula a div de datas através de um array passado
    function populateDataList(_dates){
      $("#date-list").html("");
      $.each(_dates, function(index,value){
      
        $("#date-list").append(
          ("<div class='box' id='box{id}'><div class='date'>{date}</div></div>").replace("{id}",index).replace("{date}",value)
        );
      });
    }
    populateDataList(dates);

});//end doc
</script>

I’m re-populating with the id of box box relative to the position of the date within the Array, in case it is necessary to have the same ID let me know that I correct.

Any doubt just comment ^^

  • 1

    Leonardo, your code doesn’t work properly. If you replace 04/05/2018 for 10/05/2018, he will not organize.

  • @Valdeirpsr is right, I was going to remove but I’ll find out why this happens before, in case I can’t remove.

  • The problem was the operating signal, the correct in my case is to use > <

3

You can use the function sort to compare which higher value and organize them.

Following example commented:

/* Captura todos os elementos data */
let $datesElement = document.querySelectorAll(".date")

/* Organiza do maior para o menor */
$dates = [...$datesElement].sort( (a, b) => {

  /**
   * Separa os valores através da barra. O JavaScript pois
   * não suporta operações com a data no formato dd/mm/aaaa
   */
  $dateA = a.firstChild.textContent.split("/")
  $dateB = b.firstChild.textContent.split("/")
  
  /* Cria os objetos data e captura o tempo em millisegundos para comparar qual maior */
  return new Date($dateA[2], $dateA[1], $dateA[0]).getTime() < new Date($dateB[2], $dateB[1], $dateB[0]).getTime()
});

/**
 * Percorre as datas já organizadas
 * remove o elemento .box e adiciona os 
 * organizados por data
 */
for (let $date of $dates) {
  $date.parentElement.remove();
  document.body.appendChild($date)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box" id="box1">
    <div class="date">01/05/2018</div>
</div>

<div class="box" id="box2">
    <div class="date">04/05/2018</div>
</div>

<div class="box" id="box3">
    <div class="date">19/05/2018</div>
</div>

<div class="box" id="box4">
    <div class="date">05/05/2018</div>
</div>

  • Hi valdeir, I’ll test

  • Sorry, maybe I didn’t understand how to implement, but it didn’t work

  • 1

    @Neo If possible, post the code you made on the website https://hastebin.com/. This makes it easier to analyze.

3

$(document).ready(function(){

      function toDate(value)
      {
        var from = value.split("/");
        return (new Date(from[2], from[1] - 1, from[0]));
        
      }
      var a = $('.box').sort(function (a, b) {
         //assumindo que o valor do atributo será sempre uma data válida
         var contentA = toDate($(a).attr('dueDate')).getTime();
         
         var contentB = toDate($(b).attr('dueDate')).getTime();
         
         return (contentB < contentA) ? -1 : (contentB > contentA) ? 1 : 0;
      });
    $('.box').parent().html(a);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js"></script>


<div class="box" id="box1" dueDate="01/05/2013">
    <div class="date">01/05/2013</div>
</div>

<div class="box" id="box2" dueDate="01/06/2013">
    <div class="date">01/06/2013</div>
</div>

<div class="box" id="box3" dueDate="04/05/2014">
    <div class="date">04/05/2014</div>
</div>

<div class="box" id="box4" dueDate="01/06/2015">
    <div class="date">01/06/2015</div>
</div>

<div class="box" id="box5" dueDate="08/05/2018">
    <div class="date">08/05/2018</div>
</div>

<div class="box" id="box6" dueDate="04/12/2020">
    <div class="date">04/12/2020</div>
</div>

getTime() returns the numeric value corresponding to the time of the specified date according to universal time.

compare dates in milliseconds

  • sorry, I put it on Jsfiddle to test and it didn’t work, what might have happened? https://jsfiddle.net/C2heg/3922/

  • 1

    @Neo Works yes, see https://jsfiddle.net/o5n3es6s/

  • Hi leo, thanks for sending the link, I viewed it working. I implemented recently with the @dvd format. I thank you and everyone for their contribution!

  • 1

    @Neo, just to exclaim, I put here in the code inside the function window.onload=function(){ because most of the time the user does not know where to put in the code. With this function you can put where you want. Without this function only works after HTML. No JsFiddle can’t put her!

  • ah perfect, that was it then

  • 1

    @Neo accurate, consider as a bonus :) - another learning

  • was testing on fiddle.. I realized that only interprets the day, but if the month and year are modified, continue the old oredenation...

  • 1

    Suggestion: change window.onload for $(document).ready(function () { ... }) or by $(function () { ... }) (which are equivalent), $.ready is much "faster" than onload, as you don’t have to wait for Resources as images or loader styles.

  • @Guilhermenascimento, ok, I’ve changed, Thanks, but explain to me why to improve my knowledge!

  • 1

    @Neo do not know how you saw this not, I think you scored silly. It happens, I also marked silly in ids, already edited the question

  • the window.onload first it is not a listner event, or it can be overwritten by other libs or similar, in case if you really need onload prefer to use so $(window).load(function () {}); on jQuery.... Now the difference between onload and ready is simple, onload needs to wait until all Resources have been loaded, such as images, other scripts and etc, already the jQuery.ready ($.ready, $(document).ready(function() {}) and $(function() {})) expect only that the structure of the HTML document has been loaded, ie no need to wait for other Resources ...

  • ... so if the page has many images with onload may take time from your "Sort" occur. Already ready requires only that HTML has been downloaded and rendered so that jQuery can interact with DOM.

  • @Guilhermenascimento tu é bruxo, rsrs!! Thanks!!

  • @Leo, so it was the issue of ids? straight then

Show 9 more comments

1


Can use .sort() making direct comparison of dates, just convert the format dd/MM/yyyy for yyyy/MM/dd. It will even keep their ids of each div intact, because it will only change their position:

$(document).ready(function(){

   var boxes = $('.box').get(); // pego e destaco as divs

   boxes.sort(function(a, b){
      
      var da = $('.date', a).text().split("/"); // converto p/ array o 'a'
      var db = $('.date', b).text().split("/"); // converto p/ array o 'b'
      
      da = da[2]+"/"+da[1]+"/"+da[0]; // monto no formato yyyy/MM/dd
      db = db[2]+"/"+db[1]+"/"+db[0]; // monto no formato yyyy/MM/dd
      
      return db > da; // comparo as datas
   });

   $.each(boxes, function(idx, divs){
      $('body').append(divs); // reinsiro as divs ordenadas no body
   });//end each

});//end doc
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" id="box1">
    <div class="date">01/05/2018</div>
</div>

<div class="box" id="box2">
    <div class="date">04/05/2018</div>
</div>

<div class="box" id="box5">
    <div class="date">01/07/2018</div>
</div>

<div class="box" id="box3">
    <div class="date">08/05/2018</div>
</div>

<div class="box" id="box6">
    <div class="date">01/01/2018</div>
</div>

<div class="box" id="box4">
    <div class="date">18/04/2018</div>
</div>

<div class="box" id="box5">
    <div class="date">02/02/2019</div>
</div>

  • Hi dvd, I tested now, with its format had a good adaptation, I managed to implement. Thank you and everyone who contributed!

  • Hi, I ended up reopening, because in some cases it didn’t work... or I didn’t understand it properly. I did not identify at what point we interpreted the 'date' class of html to compare it.. when I changed some dates did not reorganize the boxes

  • It works first.. but then starts not updating as I change the dates

  • Yes, each box is a file in a folder.. and outside it I have a file that loads all, with php, a include with while, so that everyone in the folder is loaded

  • in this case no, I had to do php this include with while, pq each box, eh a file. So each time q a file is created in that folder, this box automatically appears

  • I don’t get it. You’re adding elements to the page dynamically without Ajax. What do you mean? You’re reloading the page?

  • No ajax. Reload the Nav

  • Thanks for the help on chat, it was just the way to implement in my structure, solved with your order Function()!

  • oi @dvd, was continuing the implementation of the feature, and I felt the need to have the check by the hour, beyond the date.. you know how it would look in this structure?

  • 1

    I’ll take a look...

  • How this time would be displayed in HTML?

  • Ooi @dvd, in html would be in a div, next to the date, for example: <div class="status"><span class="date">25/04/2015</span> <"span class="hour">00:08:33</span></div>

  • Because the most recent idea is always shown first in the order.. and without the time, it is occurring not to appear in a few moments..

  • Blz... I’ll take a look

  • 1
  • I put the implementation time as you said @dvd, it worked correctly, thank you!!!

Show 11 more comments

Browser other questions tagged

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