DEV Community

Tim Kamanin πŸš€
Tim Kamanin πŸš€

Posted on β€’ Originally published at timonweb.com

4 1

How to get number of days in a month with JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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/

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs