gpt4 book ai didi

javascript - 根据当前日期 jQuery 按顺序显示即将到来的日期

转载 作者:行者123 更新时间:2023-11-27 22:42:42 25 4
gpt4 key购买 nike

我试图获取当前日期,然后首先对最接近的日期 div 排序日期。

我已设法获取当前日期并对其进行格式化,但我不确定如何订购?

这是我的尝试,但它似乎没有订购它们或任何东西

<div id="dates">
<div class="date"><span>10 September 2016</span></div>
<div class="date"><span>22 July 2016</span></div>
<div class="date"><span>29 August 2016</span></div>
<div class="date"><span>28 July 2016</span></div>
<div class="date"><span>5 August 2016</span></div>
</div>

var current = new Date();
console.log(current);

var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

var elems = $.makeArray($(".date"));

var d = current.getDate();
var m = months[current.getMonth()];
var y = current.getFullYear();

var formattedDate = d + " " + m + " " + y;

console.log(formattedDate);

elems.sort(function(a, b) {
return formattedDate > elems.text() );
});

$("#dates").html(elems);

谢谢

最佳答案

要实现您的要求,将值转换为日期并与当前日期进行比较会容易得多。从那里您可以 sort() .date 元素并将它们 append() 到其容器中,如下所示:

var now = new Date();
$(".date").sort(function(a, b) {
var aDiff = new Date($(a).text().trim()) - now;
var bDiff = new Date($(b).text().trim()) - now;
return aDiff < bDiff ? -1 : aDiff > bDiff ? 1 : 0;
}).appendTo('#dates').filter(function() {
return new Date($(this).text().trim()) - now < 0;
}).appendTo('#dates');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="dates">
<div class="date"><span>10 September 2016</span></div>
<div class="date"><span>22 July 2016</span></div>
<div class="date"><span>29 August 2016</span></div>
<div class="date"><span>28 July 2016</span></div>
<div class="date"><span>5 August 2016</span></div>
</div>

关于javascript - 根据当前日期 jQuery 按顺序显示即将到来的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com