Skip to content

Instantly share code, notes, and snippets.

@erikthedeveloper
Last active January 2, 2017 14:55
Show Gist options
  • Select an option

  • Save erikthedeveloper/2a698bd446f141996c3d1397bf9ef356 to your computer and use it in GitHub Desktop.

Select an option

Save erikthedeveloper/2a698bd446f141996c3d1397bf9ef356 to your computer and use it in GitHub Desktop.
Medium: daysInMonth
/**
* Given a date, how many days are in the month?
* Peek ahead to "next month" and look back to "last day of target month" via date=0
* @param {Date} targetMonthDate
* @return int
*/
function daysInMonth(targetDate) {
// Create a new Date for the "next month"
// Also discard date's date (set to 1) to avoid any overflow
// Example: Attempting to set date to February 31 when there are only 28 days
const nextMonth = new Date(targetDate.getFullYear(), targetDate.getMonth() + 1, 1);
// Setting nextMonth's date to 1 would give us the first date of nextMonth.
// Setting nextMonth's date to 0 gives us the last day of previous month.
const lastDayOfTargetMonth = new Date(nextMonth.getFullYear(), nextMonth.getMonth(), 0);
// Example, if last day of month is October 31st, daysInMonth = 31;
const daysInMonth = lastDayOfTargetMonth.getDate();
return daysInMonth;
}
/* The same thing, shortened up a bit */
const daysInMonth = (date) =>
(new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment