How do I sort a list by date/time? in my application, the date/time format is "Mon, Nov 1 | 8:30 PM" when I try to convert the string into date getting an invalid date as o/p. Help me to sort a list by date/time.
the date/time "Mon, Nov 1 | 8:30 PM" don't have 'year'
You can parse the strings to values that sort as required. If the year isn't important, that makes it easier.
Convert the month to a number, convert hours to 24 hour time then pad to two digits so that for example "Mon, Nov 1 | 8:30 PM" becomes 11012030.
E.g.
function parseMyDate(s) {
let z = n => ('0'+n).slice(-2);
let months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
let [d, M, D, H, m, ap] = s.toLowerCase().split(/\W+/);
return `${months[M]}${z(D)}${z(H%12 + (ap == 'am'?0:12))}${z(m)}`;
}
let d = 'Mon, Nov 1 | 8:30 PM';
console.log(`${d} -> ${parseMyDate(d)}`); // 11012030
let data = ['Mon, Nov 1 | 8:30 PM',
'Mon, Nov 1 | 12:00 PM',
'Sun, Oct 30 | 8:30 AM',
'Mon, Nov 1 | 8:30 AM'];
console.log(data.sort((a, b) => parseMyDate(a) - parseMyDate(b)));
I have hardcoded and trimmed that '|' character from the date/time format. Able to sort refer the below snippet. As per below comments, getTime() o/p may vary depends on the browser
let unsortedDate = [ "Tue, Nov 2 6:25 PM",
"Wed, Oct 28 12:30 AM",
"Mon, Nov 8 3:05 AM",
"Mon, Nov 1 8:30 PM"];
var sort = [];
unsortedDate.forEach(date => {
sort.push([ date, new Date(date).getTime() ]);
})
console.log(sort);
sort.sort( (a, b) => a[1] - b[1] );
let sorted_array = sort.map(arr => arr[0])
console.log(sorted_array)