From 1bd06c9ee6aeaf7aeaa808bdb5f68aaed5405f93 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 20 Jun 2021 12:57:01 +0300 Subject: [PATCH] Update and rename getMonthDays.md to daysInMonth.md --- snippets/daysInMonth.md | 20 ++++++++++++++++++++ snippets/getMonthDays.md | 23 ----------------------- 2 files changed, 20 insertions(+), 23 deletions(-) create mode 100644 snippets/daysInMonth.md delete mode 100644 snippets/getMonthDays.md diff --git a/snippets/daysInMonth.md b/snippets/daysInMonth.md new file mode 100644 index 000000000..d4728bcfc --- /dev/null +++ b/snippets/daysInMonth.md @@ -0,0 +1,20 @@ +--- +title: daysInMonth +tags: date,beginner +firstSeen: 2021-06-13T05:00:00-04:00 +--- + +Gets the number of days in the given `month` of the specified `year`. + +- Use the `new Date()` constructor to create a date from the given `year` and `month`. +- Set the days parameter to `0` to get the last day of the previous month, as months are zero-indexed. +- Use `Date.prototype.getDate()` to return the number of days in the given `month`. + +```js +const daysInMonth = (year, month) => new Date(year, month, 0).getDate(); +``` + +```js +daysInMonth(2020, 12)); // 31 +daysInMonth(2024, 2)); // 29 +``` diff --git a/snippets/getMonthDays.md b/snippets/getMonthDays.md deleted file mode 100644 index fdc3e0148..000000000 --- a/snippets/getMonthDays.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: getMonthDays -tags: date,intermediate ---- - -Get the number of days in the month according to the specified month. - -- Use `new Date(year, monthIndex, day)`, set the parameter day to `0` to get last day of the previous month. -- Use `Date.prototype.getDate` to get the day of month. - -```js -const getMonthDays = (year, month) => { - const today = new Date(); - - return new Date(year || today.getFullYear(), month || (today.getMonth() + 1), 0).getDate(); -}; -``` - -```js -getMonthDays(); // 30 -getMonthDays(2020, 2); // 29 -getMonthDays(2021, 2); // 28 -```