Date comparison functions (dateDiff)

You can use a dateDiff function to compare dates and return the number of days between these dates. For example, you might want to charge a premium for orders that need to be completed faster than your standard processing time.

To calculate the difference between the creation date and the due date:

function dateDiff(d1, d2) { var utcD1 = Date.UTC(d1.getFullYear(), d1.getMonth(), d1.getDate()); var utcD2 = Date.UTC(d2.getFullYear(), d2.getMonth(), d2.getDate()); return parseInt((utcD1 - utcD2) / (1000 * 60 * 60 * 24)); }


  • d1 — the later date (due date)
  • d2 — the earlier date (creation date)

This function returns the time in milliseconds, so you need to convert milliseconds into days by dividing the return value by (1000 * 60 * 60 * 24).


If you want to charge an extra $7.50 for orders that are required in 2 days or less, you would firstly define the above function to determine the difference between the creation date and due date. You would then define a deliveryCost variable in your estimateCost(order) function, as follows:


deliveryCost = order.deliveryOption.cost; // Check if a due date has been selected if (order.due) { var dueDate = new Date(order.due); // Get the order creation date. First check that the order created date // is not null. var createdDate = order.created ? new Date(order.created) : new Date(); // Find the difference in days between the order creation date, // and when the order is due. var numberOfDays = dateDiff(dueDate, createdDate) // If the order is required within 2 days, add $7.50 to the cost. if (numberOfDays <= 2) { deliveryCost = deliveryCost + 7.5; } }

You cannot reference lead time or working days in your cost scripts as there are no Order object attributes for these values.