From d411e686697f60192430088063a1dc669db59e80 Mon Sep 17 00:00:00 2001 From: Nhon Dinh Date: Sat, 10 Oct 2020 00:36:54 +0700 Subject: [PATCH 1/2] add lastDateOfMonth --- snippets/lastDateOfMonth.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 snippets/lastDateOfMonth.md diff --git a/snippets/lastDateOfMonth.md b/snippets/lastDateOfMonth.md new file mode 100644 index 000000000..942574544 --- /dev/null +++ b/snippets/lastDateOfMonth.md @@ -0,0 +1,18 @@ +--- +title: lastDateOfMonth +tags: date,intermediate +--- + +Get last date in current month of given date. +- Generate new date of the next month and use day 0 to get one day before it. + +```js +const lastDateOfMonth = date => { + return new Date(date.getFullYear(),date.getMonth()+1,0); +} +``` + +```js +//Current date is 10-10-2020 +lastDateOfMonth(new Date()); // 'Sat Oct 31 2020 00:00:00 GMT+0700' +``` From b19b1174e742e2f9926bd21cc2702d2658250dd0 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Fri, 9 Oct 2020 22:01:42 +0300 Subject: [PATCH 2/2] Update lastDateOfMonth.md --- snippets/lastDateOfMonth.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/snippets/lastDateOfMonth.md b/snippets/lastDateOfMonth.md index 942574544..e8fab0c30 100644 --- a/snippets/lastDateOfMonth.md +++ b/snippets/lastDateOfMonth.md @@ -3,16 +3,19 @@ title: lastDateOfMonth tags: date,intermediate --- -Get last date in current month of given date. -- Generate new date of the next month and use day 0 to get one day before it. +Returns the string representation of the last date in the given date's month. + +- Use `Date.prototype.getFullYear()`, `Date.prototype.getMonth()` to get the current year and month from the given date. +- Use the `new Date()` constructor to create a new date with the given year and month incremented by `1`, and the day set to `0` (last day of previous month). +- Omit the argument, `date`, to use the current date by default. ```js -const lastDateOfMonth = date => { - return new Date(date.getFullYear(),date.getMonth()+1,0); -} +const lastDateOfMonth = (date = new Date()) => { + let d = new Date(date.getFullYear(), date.getMonth() + 1, 0); + return d.toISOString().split('T')[0]; +}; ``` ```js -//Current date is 10-10-2020 -lastDateOfMonth(new Date()); // 'Sat Oct 31 2020 00:00:00 GMT+0700' +lastDateOfMonth(new Date('2015-08-11')); // '2015-08-30' ```