calculate startdate and enddate of week, yields a strange result when 1st of new month

I use the code below to calculate the start and enddate of the week based on the current date. As i live in sweden, the first day of the week is on a monday.

if the date is 31th of august 2021 the result is 20210830-20210905 But now, when the date becomes 1st of september 2021 the result is 20210830-20210805?

How is it even possible?

I am running this locally on a firebase cloud emulator and in the firebase cloud function live, the result are the same.

function currentWeeklyId() {
    const dateNow = new Date();
    // First day is the day of the month
    const first = dateNow.getDate() - dateNow.getDay() + 1;
    const last = first + 6;

    const fDay = new Date(dateNow.setDate(first));
    const lDay = new Date(dateNow.setDate(last));

    var firstMonth = fDay.getMonth() + 1;
    if (firstMonth < 10) firstMonth = '0' + firstMonth;
    var firstDay = fDay.getDate();
    if (firstDay < 10) firstDay = '0' + firstDay;

    var lastMonth = lDay.getMonth() + 1;
    if (lastMonth < 10) lastMonth = "0" + lastMonth;
    var lastDay = lDay.getDate();
    if (lastDay < 10) lastDay = "0" + lastDay;

    const docId = dateNow.getFullYear() + firstMonth + firstDay + "-" + dateNow.getFullYear() + lastMonth + lastDay;

    return docId;
}

Answer

The problem lies on this line

const lDay = new Date(dateNow.setDate(last));

You are changing the date, but not the month. dateNow points to August month.

The lDay should reference new fDay while setting date.

const lDay = new Date(dateNow.setDate(fDay.getDate()+6))

function currentWeeklyId() {
  const dateNow = new Date();
  // First day is the day of the month
  const first = dateNow.getDate() - dateNow.getDay() + 1;

  const fDay = new Date(dateNow.setDate(first));
  const lDay = new Date(dateNow.setDate(fDay.getDate() + 6))

  var firstMonth = fDay.getMonth() + 1;
  if (firstMonth < 10) firstMonth = '0' + firstMonth;
  var firstDay = fDay.getDate();
  if (firstDay < 10) firstDay = '0' + firstDay;

  var lastMonth = lDay.getMonth() + 1;
  if (lastMonth < 10) lastMonth = "0" + lastMonth;
  var lastDay = lDay.getDate();
  if (lastDay < 10) lastDay = "0" + lastDay;

  const docId = dateNow.getFullYear() + firstMonth + firstDay + "-" + dateNow.getFullYear() + lastMonth + lastDay;

  return docId;
}