user12
user12

Reputation: 15

End date of the week for the current month

I'm generating a report on a weekly basis(say,friday), i'll need end of week date for every month. If its a new month then return last date of the month.. i'm getting first date here: -

var firstDay = new Date(date.getFullYear(), date.getMonth(), 1); 

But cannot proceed.

Upvotes: 1

Views: 63

Answers (3)

Karan
Karan

Reputation: 12619

Try using below function.

function getWeekEndDates(date) {
  let year = date.getFullYear();
  let month = date.getMonth();
  let firstDay = new Date(year, month, 1);
  let lastDay = new Date(year, month + 1, 0);
  let weekEnds = [];

  let dateFriday = firstDay;
  if (firstDay.getDay() !== 5) {
    dateFriday = new Date(year, month, 1 + ((12 - firstDay.getDay()) % 7));
    weekEnds.push(firstDay);
  }

  while (dateFriday.getMonth() === month) {
    weekEnds.push(dateFriday);
    dateFriday = new Date(year, month, dateFriday.getDate() + 7);
  }

  if (lastDay.getDay() !== 5) {
    weekEnds.push(lastDay);
  }

  return weekEnds;
}

getWeekEndDates(new Date()).forEach(x => console.log(x.toDateString()));
getWeekEndDates(new Date(2020, 0, 1)).forEach(x => console.log(x.toDateString()));
getWeekEndDates(new Date(2021, 0, 1)).forEach(x => console.log(x.toDateString()));

Upvotes: 1

Konrad Klockgether
Konrad Klockgether

Reputation: 405

Check out RRule package. It gives you very much possibilities for date and time intervals. It works with the rules like in calendars.

For your case. Every friday:

import { RRule } from 'rrule'

const rule = new RRule({
  freq: RRule.WEEKLY,
  interval: 1,
  byweekday: [RRule.FR],
})

// fridays in interval, you will got an array of dates
rule.between(new Date(Date.UTC(2012, 7, 1)), new Date(Date.UTC(2012, 8, 1)))

Upvotes: 0

Kamil
Kamil

Reputation: 2862

There is no feature provided directly by the JavaScript to get such info, but you can do it on your own, by calculating the last friday of the month, for example like this

function lastFridayOfMonth(year, month) {
    // if month will start from one not from 0  then we will have month + 1
    var lastDay = new Date(year, month + 2, 0); 
    var lastDayNumber = 5;
    if(lastDay.getDay() < lastDayNumber) {
        lastDay.setDate(lastDay.getDate() - 7);
    }
    lastDay.setDate(lastDay.getDate() - (lastDay.getDay() - lastDayNumber));
    return lastDay;
}

Upvotes: 1

Related Questions