Update and rename getMonthDays.md to daysInMonth.md

This commit is contained in:
Isabelle Viktoria Maciohsek
2021-06-20 12:57:01 +03:00
committed by GitHub
parent da406b20b9
commit 1bd06c9ee6
2 changed files with 20 additions and 23 deletions

20
snippets/daysInMonth.md Normal file
View File

@ -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
```

View File

@ -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
```