jherax/array-sort-by

sort by dateTime

nunaram opened this issue · 4 comments

Hi, does it sort dateTime? Is any way to sort it.

It depends on the format used, remember that Date object in JavaScript is different from other languages, thus, you can pass a string-date in the formats supported by JavaScript:

If possible, set the date format from backend, e.g.:

// ISO 8601 format
date = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");

// In JavaScript milliseconds
date = myDate.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;

Otherway, you need to provide the callback to transform the string into a JavaScript Date, see some examples:

You can build your own function to transform the DateTime in order to build the JavaScript Date, see this gist as example --> formatDate.js

var MSDATE = /Date/;
sortBy(arrayDates, function(date) {
    // date in .Net AJAX format
    // date = "/Date(590104800000)/"
    if (MSDATE.test(date)) {
        date = +date.replace(/\D+/g, '');  
    }
    return new Date(date);
});

Please correct my understanding on solution provided above, would be sorting based on Date field without considering time.
So in case we want to consider even time field then how should we go about?
Ex: we have 3 dates as
Input : 2019-05-03 18:00, 2019-05-03 10:00 and 2019-05-03 8:00
Expected : 2019-05-03 8:00 , 2019-05-03 10:00, 2019-05-03 18:00

@nivuhebs, of course you can provide any kind of date. When you pass the callback to transform the date, just provide a correct date format that Javascript can understand.

At the top of this thread, I put the link:

See: JavaScript Date Formats

#7 (comment)


ISO Dates (Date-Time)
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):

Example
var d = new Date("2015-03-25T12:00:00Z");


Then, in your case, considering you have an array of strings representing dates, you can try to format the date to a valid ISO format, something like this...

sortBy(array, (item) => {
  // "2019-05-03 8:00" 
  const [date, time] = item.split(' ');
  // build format YYYY-MM-DDTHH:MM
  const hhmm = `0${time}`.slice(-5);
  return new Date(`${date}T${hhmm}`);
}) ;

Thank you... It works. i think we need to handle hh to accept >10hrs not to have 0 appended