Martin
Martin

Reputation: 121

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;
}

Upvotes: 0

Views: 31

Answers (2)

Shaunak D
Shaunak D

Reputation: 20636

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;
}

Upvotes: 1

Amethystx87
Amethystx87

Reputation: 488

Seems for your calculation of lastDay you need to add in the original date- as of right now you’re just setting the day of the month rather than adding.

lDay = dateNow.setDate(dateNow.getDate() + last)

Upvotes: 0

Related Questions