Nearest future date from a list of dates
Nearest future date from a list of dates
by lshettyl
HTML
<ul class="locations">
<li>
<span class="date">01-Jun-2015</span>
<span class="location">London</span>
</li>
<li>
<span class="date">15-Jun-2015</span>
<span class="location">Paris</span>
</li>
<li>
<span class="date">03-Jul-2015</span>
<span class="location">Berlin</span>
</li>
<li>
<span class="date">16-Jun-2015</span>
<span class="location">Milan</span>
</li>
<li>
<span class="date">20-Jul-2015</span>
<span class="location">Madrid</span>
</li>
<li>
<span class="date">07-Aug-2015</span>
<span class="location">Lisbon</span>
</li>
</ul>
<p class="next-date">
<strong>Next date and location: </strong><br/>
</p>
CSS
.locations .nearest {
color: green;
font-size: 1.5em;
}
JavaScript
var $locations = $(".locations");
//Today's date in milliseconds
var tsToday = new Date().getTime();
//Create an array of timestamps using .map
var allDatesTimestamp = $locations.find(".date").map(function() {
//Convert text to date in milliseconds
var ts = new Date($(this).text()).getTime();
//Return only those timestamps that are greater than today
//And sort them to get the smallest/nearest timestamp as the first array item
if (ts > tsToday) {
return ts;
}
}).get().sort();
//Find all .date elements and filter out
var $elem = $locations.find(".date").filter(function() {
//Filter out the one where date equals to first item in the array as that's the nearest
return new Date($(this).text()).getTime() === allDatesTimestamp[0]
//Return the sarrounding element
//Add a class if need be, to highlight it
}).closest("li").addClass("nearest");
//Rest is simple; find and display.
$(".next-date")
.append("Date: " + $elem.find(".date").text())
.append("<br/>Location: " + $elem.find(".location").text());