function to change dates does not work
-
29-06-2021 - |
Question
With a lot of help I've done a function that checks onload if a date is a weekend or not, and if it is a sunday it must increment the day. If it is a Saturday it day has 2 added to it because unfortunately in France nobody wants to work during the weekend.
Here is the code I'm using:
<script type="text/javascript">
function getdate() {
var items = new Array();
var itemCount = document.getElementsByClassName("date");
for (var i = 0; i < itemCount.length; i++) {
items[i] = document.getElementById("date" + (i + 1)).value;
}
for (var i = 0; i < itemCount.length; i++) {
items[i] = document.getElementById("date" + (i + 1)).value;
var itemDtParts = items[i].split("-");
var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
if (itemDt.getDay() == 6) {
itemCount[i].value = itemDt.getDate()+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
if (itemDt.getDay() == 0) {
itemCount[i].value = itemDt.getDate()+ "-" + (itemDt.getMonth() < 9 ? "0" : "") + (itemDt.getMonth() + 1) + "-" + itemDt.getFullYear();
}
}
return items;
}
</script>
All works fine for checking if date is a weekend but when I'm asking date +1 it does not change.
I just would like to change Saturday and Sunday to Monday.
Thanks for the help
SP.
Solution
Where you do:
> var itemDt = new Date(itemDtParts[2], itemDtParts[1] - 1, itemDtParts[0]);
you can then do something like:
// Increment date if Saturday or Sunday
var inc = itemDt.getDay() == 0? 1 : itemDt.getDay() == 6? 2 : 0;
// Only update DOM if necessary
if (inc) {
itemDt.setDate(itemDt.getDate() + inc);
// Update DOM
}
Note that Date objects adjust if the date is set beyond the end of the month (or before the start), so setting a date of 32 January becomes 1 February.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow