Introduction

I have recently been working on a JavaScript project where I needed to sort Dates by descending order and Time by ascending order. For this project, I am already using Moment.js as my Date Time JavaScript Library. The aggregate I am sorting contains moment objects and not native Date JavaScript objects.

Sorting by the JavaScript Date object is easy enough, but I have not found many methods on sorting by Date and Time independently. Therefore, the goal of this post is to come up with a solution for sorting by descending Date and ascending Time.

Sort by Date

In JavaScript, sorting by Date and Time in either ascending or descending order is pretty much built in through the Date’s greater then ( > ) and less then ( < ) operators.

Sort by Time

With JavaScript alone, I have not found a quick and easy solution to sort specifically by time; therefore, we need to create one.

I am going to breakdown the hours, minutes and seconds then compare them individually. I am going to start with comparing hours first and only if the hours are identically I will compare minutes. If minutes are identical, I will finally compare seconds. One could easily go as precise as milliseconds, but that level of accuracy is not necessary for my needs.

Example 3

Unfortunately, as I previously stated the greater then ( > ) and less then ( < ) operators sort by Date andTime; Therefore, this approach would not work because sortByDateDesc would only ever return “0” if both of the Date and Time are identical, effectively bypassing or uselessly executing the Time sorting portion of the code.

I have decided we could segregate the Date portion into Years, Months and Days, similarly to how we sorted Times (e.g., If the Years, Months and Days are identical then compare the Time portion as we previously did).

Conclusion

By breaking down this problem, we were easily able to create a solution that works. But, I know I know you are not using Moment.js and you don’t want to use Moment.js just to sort Dates. Well, Moment.js is simply a wrapper, with amazing features, around a native Date object. You can easily alter my provided examples and use the Date object to accomplish the exact same thing. The only difference, for example, is instead of invoking the method seconds on a moment.js object, you would invoke getSeconds on a Date object.

To quickly generate the native JavaScript code, skillfully write a macro to find and replace the Date object’s getters (I.E. Find: hs. Replace: hs.get), capitalize the method names and make a couple other small tweaks.