Javascript Sort By Date On Table Not Working
Hi I cannot get sort function working on date. It changes order of the rows but it doesn't sort properly and dates are all over the place. I would like upcoming events to future ev
Solution 1:
Your date string is not in valid format. You can use string#replace()
to change the date string to MM-DD-YYYY
from DD\MM\YYYY
and then covert to date and do the comparison.
$('tr.Entries').sort(function(a,b){
var dateA = jQuery(a).find('td.event-date > a').text();
dateA = dateA.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
var dateB = jQuery(b).find('td.event-date > a').text();
dateB = dateB.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
returnnewDate(dateB).getTime() - newDate(dateA).getTime();;
}).appendTo('tbody');
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="event clearfix"><thead><tr><td>Date</td><td>Event</td><td>Location</td><td>Ticket</td></tr><trclass="space"></tr></thead><tbody><trclass="Entries"><tdclass="event-date"><ahref="#">15/04/2017</a></td><tdclass="event-title"><ahref="#">Reggae, Seggae & Sega Night</a></td><tdclass="event-location"><ahref="#">Bar Open, Fitzroy Melbourne</a></td><tdclass="event-ticket-link"><ahref="#"class="button button-normal">BUY TICKET</a></td></tr><trclass="Entries"><tdclass="event-date"><ahref="#">06/05/2016</a></td><tdclass="event-title"><ahref="#">The Sunraysia Multicultural Festival</a></td><tdclass="event-location"><ahref="#">Nowingi Place, Mildura Victoria</a></td><tdclass="event-ticket-link"><ahref="#"class="button button-normal">BUY TICKET</a></td></tr><trclass="Entries"><tdclass="event-date"><ahref="#">25/08/2017</a></td><tdclass="event-title"><ahref="#">Live N Local Winter Music Festival</a></td><tdclass="event-location"><ahref="#">Pause Bar, Balaclava</a></td><tdclass="event-ticket-link"><ahref="#"class="button button-normal">BUY TICKET</a></td></tr></tbody></table>
var dates = ['25/08/2017', '09/09/2017', '15/09/2017', '16/09/2017', '28/09/2017', '10/12/2017', '10/02/2018', '16/12/2017'];
dates.sort(function(a,b){
var dateA = a;
dateA = dateA.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
var dateB = b;
dateB = dateB.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
returnnewDate(dateA).getTime() - newDate(dateB).getTime();
});
console.log(dates);
Solution 2:
new Date()
doesn't know how to parse dates that have the day in the first section as opposed to the section. Date
requires the format MM/DD/YYYY
If you take your first date 25/08/2017
and pass it into new Date()
you will get an Invalid Date
response.
If you want this to work you'll need to make sure the date is formatted into something Date
understands so you can either do a swap programmatically or you can also pass in the parameters manually into the new Date
function
Post a Comment for "Javascript Sort By Date On Table Not Working"