For eg. Date is 2019-01-29 (Jan 29,2019) I want set month January from 29 Date to 31 Date and display as 2019-01-31 as result using JavaScript
Asked
Active
Viewed 3,455 times
-3
-
3What have you tried ? Show us some code :) – Serge K. Feb 19 '19 at 17:54
-
I suggest you follow this procedure: Get the current date, `var date = new Date()`, add one month, and then do `date.setDate(-1)` – TKoL Feb 19 '19 at 17:56
-
https://stackoverflow.com/questions/222309/calculate-last-day-of-month-in-javascript – epascarello Feb 19 '19 at 17:58
-
Possible duplicate of [Calculate last day of month in JavaScript](https://stackoverflow.com/questions/222309) and [Get first and last date of current month with JavaScript or jQuery](https://stackoverflow.com/questions/13571700) – adiga Feb 19 '19 at 17:59
2 Answers
1
//Set this to whatever date you want..
var d = '2019-02-21';
//Parse out our date object a bit..
var asOf = new Date(d);
var year = asOf.getFullYear();
var month = asOf.getMonth();
//Initially set to first day of next month..
var desiredDate = new Date(year, month + 1, 1);
//Now just subtract 1 day to make it the last day of prior month..
desiredDate.setDate(desiredDate.getDate() - 1);
//Show the date of last day in month..
console.log(`The last day of ${month + 1}/${year} is: ${desiredDate.toLocaleString().split(',')[0]}`);

Tom O.
- 5,730
- 2
- 21
- 35
0
var date = new Date();
date.setMonth(date.getMonth() + 1);
date.setDate(-1);
Setting date to -1 sets it to the last day of the previous month.

TKoL
- 13,158
- 3
- 39
- 73
-
1It shoud be `.setDate(0)` rather than `.setDate(-1)`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate#description : "For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month." And even so, this solution fails for certain days of the year. See details here: https://stackoverflow.com/a/69096049 – Aaron Dunigan AtLee Sep 08 '21 at 01:54