0

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.

Related to this question

Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65
  • This is not the standard representation of dates and times that JavaScript uses (it uses ISO 8601 format). To work with such dates you'll have to first convert them to this format – Parzh from Ukraine Nov 08 '21 at 12:16
  • Also, I'm not sure how is this related to Protractor – Parzh from Ukraine Nov 08 '21 at 12:17
  • @DimaParzhitsky, In which format we can convert this and How? using getTime() getting NaN as o/p. In Protractor, I have a validation whether a table is sorted by recently updated, for that date/time format is getting from client application as mentioned in above format. – Venkatesh Rb Nov 08 '21 at 12:48
  • Since this is an unknown format, you'll have to do this manually, using string parsing and so on – Parzh from Ukraine Nov 08 '21 at 12:49
  • If you are getting this from an app, I'd search for an option to get this in ISO 8601 in the first place, the format is pretty common. If this is an internal app developed by a sibling team in the same company, just ask them to return well-formated string (again, ISO 8601) – Parzh from Ukraine Nov 08 '21 at 12:50
  • @DimaParzhitsky—ISO 8601 would be handy but isn't essential. Parsing the OP format is perhaps 3 lines of code. The year is the only tricky bit. but may not be difficult. – RobG Nov 08 '21 at 14:34
  • @RobG Well, true. However, OP said "date/time", and ISO 8601 is a date-time format designed specifically with lexical sorting in mind; a list of compliant strings can be sorted with `.sort()` – no arguments are needed. So, If parsing a custom format is necessary at all, I'd start parsing it to ISO to save myself the work in the fututre. – Parzh from Ukraine Nov 08 '21 at 16:14

3 Answers3

0

the date/time "Mon, Nov 1 | 8:30 PM" don't have 'year'

enter image description here

步行街
  • 13
  • 2
  • that's how I am getting from the application – Venkatesh Rb Nov 08 '21 at 12:13
  • Looking at the response, you will have to split the date and time and then modify using momentjs. [MomentJS](https://momentjs.com/docs/#/use-it/) - for syntax reference. – Akshay Balwani Nov 08 '21 at 12:28
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 08 '21 at 12:35
  • This should be a comment, it's not an answer. – RobG Nov 08 '21 at 14:37
0

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)));
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

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)
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Nov 08 '21 at 14:36
  • @RobG, Is above solution not helpful for data sorting ? if so provide best solution and help me to understand. – Venkatesh Rb Nov 09 '21 at 06:41
  • No. Parsing of unsupported formats by the built–in parser is implementation dependent, you have no idea what might happen. For `new Date("fri, dec 31 12:30 AM")` Safari assumes a year of 2000, Chrome 2001, Firefox returns an invalid date so *getTime* returns *NaN*. How do you think that will sort? – RobG Nov 09 '21 at 11:00
  • @Robg Yes, I agree with that it's not right solution but still this application supports in chrome and we are executing all the scripts in chrome only. And also, BA's are not ready to update the format for date/time in application. Even I asked them functionally it's not well and good but still client prefers to stick with current format though year is not a big deal for them. No more workaround found to handle hence did in this way. – Venkatesh Rb Nov 09 '21 at 11:12
  • @RobG, Apart from date format, how do we consider that '|' character ? if we add the year on the date/time format then without removing the '|' character. we couldn't able to convert it as Date format using getTime() right. – Venkatesh Rb Nov 09 '21 at 17:29
  • The answer is to parse the string and reformat it so that it sorts as you require. You're focussing on using the built–in Date parser, which is a poor strategy. Just reformat it into say MM-DD HH:mm or MMDDHHmm and sort that. It only requires converting month name to number and am/pm to 24 hour time. Neither is difficult. – RobG Nov 09 '21 at 20:26