I want to calculate a reminderDate
by subtracting 3 days from it. However, if the resulting date
- falls on a Saturday or Sunday, it should give the date of the Friday
- falls on a Friday, it should give the date of Thursday
For example
Exchange Date ReminderDate
18.06.2020 -3 days = 15.06.2020 --> OK, because Monday
17.06.2020 -3 days = 14.06.2020 --> Sunday, must be changed to 12.06.2020
16.06.2020 -3 days = 13.06.2020 --> Saturday, must be changed to 12.06.2020
15.06.2020 -3 days = 11.06.2020 --> Friday, must be changed to 11.06.2020
I tried something like this, but neither .getDay()
nor .day()
seem to work. And dt
seems to give the date of today, and not the date of exchange
.
var exchange = NWF$("#" + varAustauschtermin).val(); // date like 18.06.2020
console.log("Exchange: " + exchange);
var reminderDate = moment(exchange, "DD.MM.YYYY").format("DD.MM.YYYY");
var dt = new Date(reminderDate);
// var reminderDate = moment(exchange, "DD.MM.YYYY").subtract(3, 'days').format("DD.MM.YYYY");
// console.log("reminderDate.day(): " + reminderDate.day());
// console.log("reminderDate.getDay(): " + reminderDate.getDay());
if(dt.getDay() == 6) { // Saturday
console.log("Saturday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(1, 'days').format("DD.MM.YYYY");
} else if (dt.getDay() == 0) { // Sunday
console.log("Sunday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(2, 'days').format("DD.MM.YYYY");
} else if (dt.getDay() == 5) { // Friday
console.log("Friday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(1, 'days').format("DD.MM.YYYY");
} else {
console.log("Weekday");
reminderDate = moment(exchange, "DD.MM.YYYY").subtract(3, 'days').format("DD.MM.YYYY");
}
console.log("Reminder Date: " + reminderDate);
Any help is appreciated!
If you are using momentjs then there is no need to switch to native Date object because everything you can do with momentjs and with much simplicity
Use momentjs day() to help you get the oridinal for a day of week
0 - Sunday 1 - Monday ... .. . 6 - Saturday
To find what date will say "Saturday" come in this week you can do like
moment().day("Saturday")
. Then there is subtract which you are already using to rewind dates by given days.Building on these above ideas you can try this helper function