const getDaysInMonth = date => new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); getDaysInMonth(new Date(2019, 1)); // 28 days in February 2019 getDaysInMonth(new Date(2019, 3)); // 30 days in April 2019
There are two things you need to understand about dates in JS to get how this function is working:
Dateobjects are null-indexed, which means 0 is January, 1 is February ..., and 11 is December;
- When we create a
Dateand provide zero as the third argument
new Date(2019, 2, 0), we literally say "the last day of the previous month.".
getDaysInMonth(new Date(2019, 1, 0)); // January 31st, 2019 getDaysInMonth(new Date(2019, 2, 0)); // February 28th, 2019 getDaysInMonth(new Date(2019, 0, 0)); // December 31, 2018
So in plain English, in
getDaysInMonth we take a date, increment a month, so we get the next month and at the same time, set a day for the next month to "0" which sets the date to the last day of the previous month, which, in turn, is our initial month. Then we use
getDate() function that returns us the day as an integer.