Published on

How to Get Start Date and End Date of Any Month in JavaScript

Authors

Basically, we can get the last day of a month by passing 0 as day while intializing Date

Here's a quick example of it.

Any Month

//  month is 0-indexed. So 0 → Jan, 11 → Dec
const month = 4; // May
const year = 2021;
const startDt = new Date(year, month, 1);
const endDt = new Date(year, month + 1, 0);

Current Month

const date = new Date();
const month = date.getMonth();
const year = date.getFullYear();
const startDt = new Date(year, month, 1);
const endDt = new Date(year, month + 1, 0);

Helper Function

export const getFirstAndLastDateOfMonth = ({
  year = undefined,
  month = undefined,
} = {}) => {
  const date = new Date();
  if (year !== undefined && month !== undefined) {
    date.setMonth(month);
    date.setFullYear(year);
  }
  const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
  const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  return {
    startDate,
    endDate,
  };
};

// getFirstAndLastDateOfMonth() → current month
// getFirstAndLastDateOfMonth({month:0, year:2021}) → Jan 2021