Last active
January 2, 2017 14:55
-
-
Save erikthedeveloper/2a698bd446f141996c3d1397bf9ef356 to your computer and use it in GitHub Desktop.
Medium: daysInMonth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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