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
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>
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.