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.
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)));