根据当前日期jQuery显示即将到来的日期

时间:2016-07-28 09:50:27

标签: javascript jquery html date

我正在尝试获取当前日期,然后首先订购最接近日期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);

由于

2 个答案:

答案 0 :(得分:1)

要实现您的需求,将值转换为日期并与当前日期进行比较会更容易。从那里你可以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>

答案 1 :(得分:0)

  

基于当前日期的最近日期

&#13;
&#13;
var element = $.makeArray($(".date"));
var array = [];
var current = new Date();

element.sort(function(a,b){
  var c = new Date($(a).text());
  var d = new Date($(b).text());
 
  return c-d;
});
for(var i in element){
   var d  = new Date($(element[i]).text());
  if(d >= current){
       $("#sorted").append(element[i])  
    } 
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dates">
  <div id="10 September 2016" class="date"><span>10 September 2016</span></div>
  <div id="22 July 2016" class="date"><span>22 July 2016</span></div>
  <div id="29 August 2016" class="date"><span>29 August 2016</span></div>
  <div id="28 July 2016" class="date"><span>28 July 2016</span></div>
  <div id="5 August 2016" class="date"><span>5 August 2016</span></div>
</div>
<h1>after sort</h1>
<div id="sorted"></div>
&#13;
&#13;
&#13;