404

If you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

There is reference to this behaviour at mozilla. Is this a reliable cross-browser feature or should I look at alternative methods?

pietrodito
  • 1,783
  • 15
  • 24
Ken
  • 77,016
  • 30
  • 84
  • 101

25 Answers25

621

var month = 0; // January
var d = new Date(2008, month + 1, 0);
console.log(d.toString()); // last day in January
IE 6:                     Thu Jan 31 00:00:00 CST 2008
IE 7:                     Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2:             Thu Jan 31 00:00:00 CST 2008
Opera 8.54:               Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27:               Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60:               Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17:         Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3:            Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)

Output differences are due to differences in the toString() implementation, not because the dates are different.

Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.

RobG
  • 142,382
  • 31
  • 172
  • 209
Grant Wagner
  • 25,263
  • 7
  • 54
  • 64
  • 20
    That seems to work perfectly well. Out of curiosity, what are you using to run the javascript on all these engines? Got everything set-up or some kind of tool? – neonski Oct 21 '08 at 17:04
  • 8
    you can use d.getDate() to get the actual day. – rynop Dec 18 '12 at 21:00
  • 42
    "just because the browsers … use 0 as the last day of the previous month does not mean they will continue to do so". Yes it does, they are required to do so by ECMA-262. – RobG Apr 30 '14 at 22:52
  • Would that logic have problems with finding the last day in Decembre? The Date() constructor would likely fail trying to resolve the 13th month in a year... – Adam Miller Dec 16 '14 at 22:31
  • 4
    Please note that using `new Date` is *so* much slower than other calculation methods that it *does not even show up on the perf chart*: http://jsperf.com/days-in-month-perf-test/6 – iCollect.it Ltd Feb 23 '15 at 09:47
  • 2
    @AdamMiller the '13th month' seems to resolve as January of the next year just fine. – Mahn Mar 31 '15 at 20:35
  • 1
    "Nonsensical" dates should resolve just fine, `new Date(2015, 0, 60)` should come out as the 1st of March 2015, because 31 days in January + 28 days in February (non-leap year) + 1 day. Just keep in mind that January=0 ... December=11 in the `Date()` constructor. – CodeManX Aug 29 '15 at 16:57
  • 7
    It doesn't work for me on Chrome 48.0.2564.116. Perhaps, this way has stopped from being the 'standard'. – xarlymg89 Feb 23 '16 at 15:49
  • I've a weird result when increasing to next month, from july to august. I do `fromDate.setMonth(fromDate.getMonth() + 1);` and `toDate.setMonth(toDate.getMonth() + 2); toDate.setDate(0);` . But for august i got toDate with the last date of september... But if instanciate new Date there is no problem... Any idea ? – Hornth May 12 '16 at 10:36
  • 1
    For those reading @CarlosAlbertoMartínezGadea comment, It does work for me in Chrome 73.0.3683.103 – callmetwan Apr 16 '19 at 17:46
  • 1
    It's true @callmetwan I've tested it on Chromium 73 and it's working fine. I don't even remember this, but I had upvoted the answer from karlipoppins. Probably a bug on that Chrome version. – xarlymg89 Apr 17 '19 at 07:39
  • That makes sense @CarlosAlbertoMartínezGadea! Thanks!! – callmetwan Apr 17 '19 at 17:50
  • This does not output a date in the correct GMT and you will get weird result if you try to use that date with anything GMT related (correct GMT should be Thu, 31 Jan 2008 06:00:00 GMT+0600 or Thu, 01 Feb 2008 18:00:00 GMT-0600 ) – Tofandel Sep 17 '19 at 21:41
  • works really well. hope no more new recommendations to come that will make this stop working – Mohammed Shareef C Jun 10 '20 at 07:59
  • @Tofandel—no, it's not. Mixing local and UTC methods like that is nonsensical. For me, starting with `new Date(2020,6,1)` returns 1 Jul, and `new Date(2020,6,21)` returns 1 Aug when both should return 30 Jul. – RobG Jun 22 '21 at 12:20
  • @RobG There was indeed a mistake, here is the correct one `var l = new Date(2020,6,21); l.setMonth(l.getMonth()+1); l.setDate(0)` – Tofandel Jun 22 '21 at 14:02
149

I find this to be the best solution for me. Let the Date object calculate it for you.

var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.

orad
  • 15,272
  • 23
  • 77
  • 113
  • 3
    It's okay, I noticed the selected answer is suggesting the same. This is the fastest and most reliable way and works regardless of the type of the calendar. For example if Date implemented something other than the Gregorian calendar it would still work. See http://intldate.codeplex.com for an example of non-Gregorian implementation of Date object. – orad Mar 12 '13 at 23:38
  • 2
    @orad: Beware of claiming something *"is the fastest"* as this method is actually considerably slower than some alternatives. Using `new Date` is *so* much slower it *does not even show up on the perf chart*: http://jsperf.com/days-in-month-perf-test/6 – iCollect.it Ltd Feb 23 '15 at 09:49
  • @TrueBlueAussie OK. I had assumed that it was faster because it was native. But you're right, it's not fast. Thanks for actually testing it. Anyways, this solution works best for me because it's concise and readable and unlike all other solutions is not bound to the Gregorian calendar. – orad Feb 23 '15 at 19:42
  • *"unlike all other solutions is not bound to the Gregorian Calendar"!!!* This algorithm returns the same values as mine for years 1-4000. http://jsfiddle.net/2973x9m3/3/ What additional date range are you claiming this will support (that would be of use)? :) – iCollect.it Ltd Feb 23 '15 at 20:04
  • 2
    Native JS Date uses Gregorian calendar only. But you could mock it with some other implementation to get other calendar types. For example see [IntlDate](http://intldate.codeplex.com/). If you have a date picker that uses Date objects to create monthly views, it doesn't care which Date implementation (native or mocked) it is using as long as they have the same interface. So using a shared interface allows switching between different Calendar types without having to know how many days are in a month on each calendar. – orad Feb 23 '15 at 21:31
  • 1
    @GoneCoding—the [jsperf link](http://jsperf.com/days-in-month-perf-test/6) is broken, do you have an update? It would be good to see alternatives and whether the speed difference persists (or even if it matters). :-) – RobG Apr 01 '21 at 03:27
83

I would use an intermediate date with the first day of the next month, and return the date from the previous day:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
Jamal
  • 763
  • 7
  • 22
  • 32
Gad
  • 41,526
  • 13
  • 54
  • 78
  • 2
    this is the best solution IMO. I tried the accepted answer but it has some bug when fetching the last of the current month. It returns today's date. Not sure why that happens though. – Gogol Mar 13 '14 at 11:26
  • 2
    I can't repro the bug. This gives me correct date in all browsers: `today = new Date(); new Date(today.getFullYear(), today.getMonth()+1, 0).toString();` – orad Apr 24 '14 at 22:35
  • This creates a Date object for the last day of the month with the time set to last millisecond (i.e. 23:59:59.999). Better to just use the method in the OP and save the extra step and Date object. – RobG Apr 30 '14 at 22:59
  • @RobG: i agree! though my solution might be easier to understand, as the notion of using 0 for the last day of the month feels a bit cluncky in my opinion. – Gad May 14 '14 at 10:47
  • Please note that using `new Date` is *so* much slower than other calculation methods that it *does not even show up on the perf chart*: http://jsperf.com/days-in-month-perf-test/6 – iCollect.it Ltd Feb 23 '15 at 09:48
  • 1
    @TrueBlueAussie i'm pretty sure that if you have perf issues in your webapp you should start by looking elsewhere than in the speed of `new Date` :) – Gad May 30 '15 at 08:15
  • So your advice would be to not let people know this solution is 100 times slower than alternatives? Surely *that sort of difference* is well worth mentioning once identified :) – iCollect.it Ltd May 30 '15 at 08:20
  • No you're right, it's worth mentionning. However I doubt it's 100 times slower since it makes 2 `new Date` calls instead of 1 so we're probably looking at twice slower. – Gad May 30 '15 at 08:59
  • According to the [ECMAScript specification](http://bclary.com/2004/11/07/#a-15.9.3), making use of the "Date" constructor as you pointed out is valid. Following the algorithm specified by the "MakeDay" function, it should handle the issue nicely. – Pablo Cabrera Oct 21 '08 at 16:30
41

In computer terms, new Date() and regular expression solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format). I keep trying different code changes to get the best performance.

My current fastest version:

After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers (note the parameters m & y must obviously be integers for this to work):

function getDaysInMonth(m, y) {
    return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}

Given the bit-shifting this obviously assumes that your m & y parameters are both integers, as passing numbers as strings would result in weird results.

JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/

JSPerf results: http://jsperf.com/days-in-month-head-to-head/5

For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.

The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5


It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.

A quick lesson in binary months:

If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.

Jan = 1  = 0001 : 31 days
Feb = 2  = 0010
Mar = 3  = 0011 : 31 days
Apr = 4  = 0100
May = 5  = 0101 : 31 days
Jun = 6  = 0110
Jul = 7  = 0111 : 31 days
Aug = 8  = 1000 : 31 days
Sep = 9  = 1001
Oct = 10 = 1010 : 31 days
Nov = 11 = 1011
Dec = 12 = 1100 : 31 days

That means you can shift the value 3 places with >> 3, XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1. Note: It turns out + is slightly faster than XOR (^) and (m >> 3) + m gives the same result in bit 0.

JSPerf results: http://jsperf.com/days-in-month-perf-test/6

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Original algo and full history (see comments): http://stackoverflow.com/questions/1810984/number-of-days-in-any-month/27810801#27810801 followed by http://stackoverflow.com/questions/1810984/number-of-days-in-any-month/27946635#27946635 – GitaarLAB Dec 13 '15 at 19:08
  • 2
    @GitaarLAB: You got a mention already and this was never exactly the same as yours, as you well know. Incremental updating of each others algorithms is not the same as "original algo". I put a lot of effort into this answer too :P – iCollect.it Ltd Dec 13 '15 at 19:14
  • @TrueBlueAussie: I only wanted to point future readers to our treasure of more info (I linked both our answers so that anyone who cares or wanting to take another go at it can look at our edit-history to see when we did *what* and *why*). I still fondly remember our full day of competition! `:)` The very first answer-version I posted had indeed an unneeded set of brackets, which were removed (for which I credited you) so we could shave of a character and end up with this one. I'm still grateful for that fun day, cheers! – GitaarLAB Dec 14 '15 at 00:13
  • 3
    Please mention that `y` and `m` variables have to be integer not string! It cause wrong calculations for example for February it returns 30. I had to use `parseInt()` function to make it work. – instead Feb 10 '17 at 14:15
  • 1
    @GoneCoding yo must be fun at parties, really enjoyed your answer :) – Abdul Rehman Feb 11 '22 at 13:33
  • Is this solution returning correct number of days for the month of February? (included JSFiddle doesn't) – Mariusz Dec 10 '22 at 18:31
  • @Mariusz please provide the input you used, month and year. Feb should always be passed as 2. – iCollect.it Ltd Dec 11 '22 at 20:32
30

My colleague stumbled upon the following which may be an easier solution

function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

stolen from http://snippets.dzone.com/posts/show/2099

lebreeze
  • 5,094
  • 26
  • 34
21

A slight modification to solution provided by lebreeze:

function daysInMonth(iMonth, iYear)
{
    return new Date(iYear, iMonth, 0).getDate();
}
Nigel
  • 1,291
  • 11
  • 7
  • 3
    This should be `return new Date(iYear, 1 + iMonth, 0).getDate();` to be equivalent to @lebreeze's solution. – Moos Apr 10 '20 at 04:52
15

I recently had to do something similar, this is what I came up with:

/**
* Returns a date set to the begining of the month
* 
* @param {Date} myDate 
* @returns {Date}
*/
function beginningOfMonth(myDate){    
  let date = new Date(myDate);
  date.setDate(1)
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);   
  return date;     
}

/**
 * Returns a date set to the end of the month
 * 
 * @param {Date} myDate 
 * @returns {Date}
 */
function endOfMonth(myDate){
  let date = new Date(myDate);
  date.setDate(1); // Avoids edge cases on the 31st day of some months
  date.setMonth(date.getMonth() +1);
  date.setDate(0);
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  return date;
}

Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.

The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.

Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.

Eric
  • 573
  • 1
  • 5
  • 11
  • 1
    Your `endOfMonth` fails for certain values of `myDate`. See my posted answer for details. – Aaron Dunigan AtLee Sep 08 '21 at 01:46
  • Good catch, that can be remedied by calling `setDate(1)` before the `setMonth` call though. I updated the answer to include this, thanks. – Eric Sep 09 '21 at 06:43
8

How NOT to do it

Beware of any answers for the last of the month that look like this:

var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)

This works for most dates, but fails if date is already the last day of the month, on a month that has more days than the following month.

Example:

Suppose date is 07/31/21.

Then last.setMonth(last.getMonth() + 1) increments the month, but keeps the day set at 31.

You get a Date object for 08/31/21,

which is actually 09/01/21.

So then last.setDate(0) results in 08/31/21 when what we really wanted was 07/31/21.

Aaron Dunigan AtLee
  • 1,860
  • 7
  • 18
  • This is a good catch. Sticking a `last.setDate(1)` before incrementing the month should remedy this, but without this step it will fail in some cases as you point out. – Eric Sep 09 '21 at 06:45
  • 6
    That's a good catch but would be better kept as a comment to the answer you're referring to since you offer no solution to the actual question. – Valentin Klinghammer Jan 26 '22 at 14:35
6

try this one.

lastDateofTheMonth = new Date(year, month, 0)

example:

new Date(2012, 8, 0)

output:

Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
artsylar
  • 2,648
  • 4
  • 34
  • 51
  • 8
    Remember, though, that months are zero-based, so passing "8" as the month is really September, not August. – Steve J Aug 30 '13 at 12:54
5

This works for me. Will provide last day of given year and month:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);
3

This one works nicely:

Date.prototype.setToLastDateInMonth = function () {

    this.setDate(1);
    this.setMonth(this.getMonth() + 1);
    this.setDate(this.getDate() - 1);

    return this;
}
ZGski
  • 2,398
  • 1
  • 21
  • 34
Josue
  • 31
  • 5
3

You can get the First and Last Date in the current month by following the code:

var dateNow = new Date();  
var firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1);  
var lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);

or if you want to format the date in your custom format then you can use moment js

var dateNow= new Date();  
var firstDate=moment(new Date(dateNow.getFullYear(),dateNow.getMonth(), 1)).format("DD-MM-YYYY");  
var currentDate = moment(new Date()).format("DD-MM-YYYY"); //to  get the current date var lastDate = moment(new
 Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0)).format("DD-MM-YYYY"); //month last date
Alfabravo
  • 7,493
  • 6
  • 46
  • 82
Rinku Choudhary
  • 1,529
  • 1
  • 13
  • 22
2

Below function gives the last day of the month :

function getLstDayOfMonFnc(date) {
  return new Date(date.getFullYear(), date.getMonth(), 0).getDate()
}

console.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29
console.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28
console.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30
console.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31

Similarly we can get first day of the month :

function getFstDayOfMonFnc(date) {
  return new Date(date.getFullYear(), date.getMonth(), 1).getDate()
}

console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Sujay U N
  • 4,974
  • 11
  • 52
  • 88
2

This will give you current month first and last day.

If you need to change 'year' remove d.getFullYear() and set your year.

If you need to change 'month' remove d.getMonth() and set your year.

var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var fistDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth(), 1).getDay())];
 var LastDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDay())]; 
console.log("First Day :" + fistDayOfMonth); 
console.log("Last Day:" + LastDayOfMonth);
alert("First Day :" + fistDayOfMonth); 
alert("Last Day:" + LastDayOfMonth);
Himanshu kukreja
  • 74
  • 1
  • 1
  • 6
2

Try this:

function _getEndOfMonth(time_stamp) {
    let time = new Date(time_stamp * 1000);
    let month = time.getMonth() + 1;
    let year = time.getFullYear();
    let day = time.getDate();
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        case 2:
            if (_leapyear(year))
                day = 29;
            else
                day = 28;
            break
    }
    let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
    return m.unix() + constants.DAY - 1;
}

function _leapyear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
1

Here is an answer that conserves GMT and time of the initial date

var date = new Date();

var first_date = new Date(date); //Make a copy of the date we want the first and last days from
first_date.setUTCDate(1); //Set the day as the first of the month

var last_date = new Date(first_date); //Make a copy of the calculated first day
last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month
last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month

console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Tofandel
  • 3,006
  • 1
  • 29
  • 48
1
const today = new Date();

let beginDate = new Date();

let endDate = new Date();

// fist date of montg

beginDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`

);

// end date of month 

// set next Month first Date

endDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`

);

// deducting 1 day

endDate.setDate(0);
chou
  • 31
  • 2
0
function getLastDay(y, m) {
   return 30 + (m <= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 && y % 4 != 0 || !(y % 100 == 0 && y % 400 == 0)); 
}
Ashish
  • 8,441
  • 12
  • 55
  • 92
0

set month you need to date and then set the day to zero ,so month begin in 1 - 31 in date function then get the last day^^

var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate();
console.log(last);
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
0

I know it's just a matter of semantics, but I ended up using it in this form.

var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);

Since functions are resolved from the inside argument, outward, it works the same.

You can then just replace the year, and month / year with the required details, whether it be from the current date. Or a particular month / year.

Rudi Strydom
  • 4,417
  • 5
  • 21
  • 30
0

If you need exact end of the month in miliseconds (for example in a timestamp):

d = new Date()
console.log(d.toString())
d.setDate(1)
d.setHours(23, 59, 59, 999)
d.setMonth(d.getMonth() + 1)
d.setDate(d.getDate() - 1)
console.log(d.toString())
Gungnir
  • 231
  • 2
  • 5
0

The accepted answer doesn't work for me, I did it as below.

$( function() {
  $( "#datepicker" ).datepicker();
  $('#getLastDateOfMon').on('click', function(){
    var date = $('#datepicker').val();

    // Format 'mm/dd/yy' eg: 12/31/2018
    var parts = date.split("/");

    var lastDateOfMonth = new Date();
                lastDateOfMonth.setFullYear(parts[2]);
                lastDateOfMonth.setMonth(parts[0]);
                lastDateOfMonth.setDate(0);

     alert(lastDateOfMonth.toLocaleDateString());
  });
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
<button id="getLastDateOfMon">Get Last Date of Month </button>
 
 
</body>
</html>
TIGER
  • 2,864
  • 5
  • 35
  • 45
0

This will give you last day of current month.

notes: on ios device include time. #gshoanganh

var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
gshoanganh
  • 137
  • 1
  • 3
0

if you just need to get the last date of a month following worked out for me.

var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();

const lastDay =  new Date(year, month +1, 0).getDate();
console.log(lastDay);

try it out here https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php

SKM
  • 355
  • 4
  • 11
-1

In my case, this code was useful

end_date = new Date(2018, 3, 1).toISOString().split('T')[0]
console.log(end_date)
Soulduck
  • 569
  • 1
  • 6
  • 17