Updating date in Javascript

I’m trying to create a simple “availability schedular” from scratch using Python, Javascript and a bit of Bootstrap (and eventually Django). I know a bit of Python but am new to Javascript.

Project is on fiddle here:
https://jsfiddle.net/surista/a85y7x31/21/

I am trying to show just one week at a time (Sun – Sat), with three header rows: First header is current month and year based on the Sunday of week currently being shown, second row the days of the week, third row is the dates. Below that I have Previous and Next buttons to move forward / backward a week.

When the page is launched, it defaults to the initial week starting from the most recent Sunday, the table and dates are created dynamically. I have this working fine.

today = new Date();

This is used as the basis for initially populating the table with the current week. Right nowe, if you launch the page, today is ‘Mon Dec 27 2021’, and the table shows the current week from the most recent Sunday – ie, Sun Dec 26 2021.

I have three functions that move the week back and forth:

function addDays(dateObj, numDays) {
  dateObj.setDate(today.getDate() + numDays);
  return dateObj;
}

function nextWeek() {
  today = addDays(new Date(), 7);
  showWeek(today);
}

function previousWeek() {
  today = addDays(new Date(), -7);
  showWeek(today);
}

Clicking ‘Previous’ a few times updates fine until Sun Nov 28, and then the month flipping back seems to break it. Ditto going forward with Next. If I go Next, then Previous, I should end up where I started, instead it goes to Sun Jan 2 (as it should) then Sun 21 Nov.

Basically it seems to work perfectly until the month changes. I have a function that I use to pull the days of the month:

function daysMonth(xMonth, xYear) {
  daysInCurrentMonth = 32 - new Date(xYear, xMonth, 32).getDate();
  return daysInCurrentMonth;
}

I’ve tested this and it seems to be working exactly as expected, and I’m always passing in the current base date, so not sure why this wouldn’t be working.

Any thoughts on what I should be looking at?