2

I have divs with data attribute data-submit-date and i want to sort them based on the value of this attribute which is date format.

here's the code for one of the divs:

<div class="article" data-submit-date="2017-09-12T05:45:36.951Z">
     <h1>aaaaA</h1>
</div>

my attempts:

$divss = $(".article");
    var alphaOrderDivs = $divss.sort(function (a, b) {
    return $(a).data("submit-date") > $(b).data("submit-date"); 
});
$(".articles").html(alphaOrderDivs);

I replaced this line $(a).data("submit-date") with Date.parse($(a).data("submit-date")) but it fails. Can anyone help me?

Thank In Advance

1

2 Answers 2

1

Try the following

var articles = $.makeArray($(".article"));
articles.sort(function(a, b) {
   return new Date($(a).data("submit-date")) < new Date($(b).data("submit-date"));
});

Snippet

var articles = $.makeArray($(".article"));
    articles.sort(function(a, b) {
       return new Date($(a).data("submit-date")) < new Date($(b).data("submit-date"));
    });
    console.log(articles);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article" data-submit-date="2017-09-10T05:45:36.951Z">
     <h1>aaaaA</h1>
</div>
<div class="article" data-submit-date="2017-09-12T05:45:36.951Z">
     <h1>aaaaA</h1>
</div>
<div class="article" data-submit-date="2017-09-11T05:45:36.951Z">
     <h1>aaaaA</h1>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Use the getTime() method as follows:

 $divss = $(".article");
 var alphaOrderDivs = $divss.sort(function (a, b) {
   return new Date($(a).data("submit-date")).getTime() > new Date($(b).data("submit-date")).getTime(); 
 });
 $(".articles").html(alphaOrderDivs);

The getTime() method of the Date object will parse your time into milliseconds and will hence help you compare them.

1 Comment

Yes you can compare Date objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.