Update and rename getMonthDays.md to daysInMonth.md
This commit is contained in:
committed by
GitHub
parent
da406b20b9
commit
1bd06c9ee6
20
snippets/daysInMonth.md
Normal file
20
snippets/daysInMonth.md
Normal 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
|
||||
```
|
||||
@ -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
|
||||
```
|
||||
Reference in New Issue
Block a user