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.
Advertisement
Answer
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.
JavaScript
x
17
17
1
function parseMyDate(s) {
2
let z = n => ('0'+n).slice(-2);
3
let months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
4
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
5
let [d, M, D, H, m, ap] = s.toLowerCase().split(/W+/);
6
return `${months[M]}${z(D)}${z(H%12 + (ap == 'am'?0:12))}${z(m)}`;
7
}
8
9
let d = 'Mon, Nov 1 | 8:30 PM';
10
console.log(`${d} -> ${parseMyDate(d)}`); // 11012030
11
12
let data = ['Mon, Nov 1 | 8:30 PM',
13
'Mon, Nov 1 | 12:00 PM',
14
'Sun, Oct 30 | 8:30 AM',
15
'Mon, Nov 1 | 8:30 AM'];
16
17
console.log(data.sort((a, b) => parseMyDate(a) - parseMyDate(b)));