Skip to content
Advertisement

arranging the records in customised way

Sort Procedure First sort by the delivered date & in case of multiple records on same date sort by delivered time (Note: if a record has both ordered and Delivered Date ,it should be sorted by Delivered date only)

08-JUN: 03.00, 08-JUN: 04.00

Then look at the ordered date without delivered date which also exists for 08-JUN & sort by ordered date if multiple records on same date sort by ordered time

08-JUN: 02.00

Then go back to the next delivered date & in case of multiple records sort by delivered time

09-JUN: 01.00, 09-JUN: 12.00

Then look at the ordered date without delivered date which also exists for 09-JUN & sort by ordered date if multiple records on same date sort by ordered time

09-JUN: 14.00

JavaScript

//Output should be like the following .-> ordered date orderTime DeliveredDate DeliveredTime

JavaScript

JavaScript

Advertisement

Answer

In your output, the last two must be reversed. Here’s the corrected comparison order. It assumes time will be present when date is there.

JavaScript

Note: For comparing two time values, you shouldn’t rely on String’s natural ordering. For example: It considers 11 < 9. If you always have 0 prefixed for hours 0 to 9, then you are good.

Another simpler way

In essence, you want to compare two Date/time from two objects (let me call it MyDateTime as the class name) i.e., given two MyDateTime instances, you want to pick the date and time of order – if not present, pick the date and time of delivery otherwise.

Once you have a date and time pair (either order/delivery) compare them with the other date and time pair of some other MyDateTime instance.

Let me define two helper functions for getting the Date and Integer objects to be used for comparison.

JavaScript

Then, we can write a simple comparator as:

JavaScript

P.S: Java Date class is not recommended and must be treated as deprecated. Check on the Java 8+ alternate for it.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement