DEV Community

loading...

How to get number of days in a month with JavaScript

timonweb profile image Tim Kamanin 🚀 Originally published at timonweb.com ・1 min read
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:

  1. Months in JavaScript Date objects are null-indexed, which means 0 is January, 1 is February ..., and 11 is December;
  2. When we create a Date and provide zero as the third argument new Date(2019, 2, 0), we literally say "the last day of the previous month.".

Examples:

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.

Originally posted at: https://timonweb.com/tutorials/how-to-get-number-of-days-in-a-month-with-javascript/

Discussion

pic
Editor guide