Skip to content Skip to sidebar Skip to footer

Datejs - Do Not Include Weeknds

I have DateJS set up on my website to give users the ability to know when they will receive their package. I am utilizing DateJS script to do this. I need to modify the script so t

Solution 1:

I wouldn't use a date library at all for this, it's very straight forward.

It seems goods only travel on business days, so you need a function that adds business days rather than your current algorithm, something like the answers to exclude weekends in javascript date calculation.

The following does something similar to just add business days, it's only efficient for a small number of days (say 0 to 10).

/* Add business days to a date.
** @param {Date} date - date to start from
** @param {number} deliveryDays - positive integer
** @returns {Date} a new Date object for the delivery date
*/functiongetDeliveryDate(date, deliveryDays) {
  // Default delivery is 3 days
  deliveryDays = typeof deliveryDays == 'undefined'? 3 : deliveryDays;
  // Copy date so don't modify originalvar d = newDate(+date);
  // Add days. If land on a Saturday or Sunday, move another daywhile (deliveryDays--) {
    d.setDate(d.getDate() + 1);
    if (!(d.getDay() % 6)) ++deliveryDays;
  }
  return d;
}
 
// Some examples
[
 [newDate(2017,0,7),3],  // Saturday start, 3 day delivery
 [newDate(2017,0,8),1],  // Sunday start, 1 day delivery
 [newDate(2017,0,13),1], // Friday start, 1 day delivery
 [newDate(2017,0,13),3], // Friday start, 3 day delivery
 [newDate(2017,0,9), 3], // Monday start, 3 day delivery
 [newDate(2017,0,8), 7]  // Sunday start, 7 day delivery
].forEach(function(d) {
  console.log('Ordered day  : ' + d[0].toString() + 
              '\nDelivery days: ' + d[1] +
              '\nDelivery on  : ' + getDeliveryDate(d[0], d[1]));
});

Solution 2:

You're only looking at weekends for the final date after adding days, not looking at weekends as the start or (in the case of 3) in between days. Why not a function like

functionaddDays(date, daysToAdd) {
    for (let i=0; i<daystoAdd; i++) {
        let nextDay = date.addDays(1);
        if (nextDay.is().saturday()) {
            nextDay = date.next().monday();
        }
        date = nextDay;
    }
 returndate;
 }

Then you just need to call that function for each of your spans:

$('.fromDate-1').html(addDays(Date.today(), 3));

Is that the problem you were trying to solve?

Post a Comment for "Datejs - Do Not Include Weeknds"