How to get number of days in a month with JavaScript

timonweb

Tim Kamanin ๐Ÿš€

Posted on January 2, 2020

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/

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
timonweb
Tim Kamanin ๐Ÿš€

Posted on January 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About