How to get number of days in a month with JavaScript
Tim Kamanin ๐
Posted on January 2, 2020
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:
-
Months in JavaScript
Date
objects are null-indexed, which means 0 is January, 1 is February ..., and 11 is December; - When we create a
Date
and provide zero as the third argumentnew 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/
๐ ๐ช ๐
๐ฉ
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
webdev Breaking Away from JSON: A New Approach to Data Transport in Web Development
November 2, 2024