I've been using Javascript's Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected, the code below produces March.
My code looks something like this:
current = new Date();
current.setMonth(current.getMonth()+1); //If today is Jan, expect it to be Feb now
This code worked everyday up until today. Is this a Javascript bug or am I going about this the wrong way?
You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.
Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.
That way, the day "last day of Jan" becomes "last day of Feb".
EDIT:
Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).
Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:
var now = new Date();
if (now.getMonth() == 11) {
var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.
I overcame my brief bout of laziness, wrote one, and decided to share!
Solution:
(new Date().getMonth()+1)%12 + 1
Just to be clear why this works, let me break down the magic!
It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.
Proof of concept:
> for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
next month for 1: 2
next month for 2: 3
next month for 3: 4
next month for 4: 5
next month for 5: 6
next month for 6: 7
next month for 7: 8
next month for 8: 9
next month for 9: 10
next month for 10: 11
next month for 11: 12
next month for 12: 1
So there you have it.
You can use the date.js library:
http://code.google.com/p/datejs/
And just do this
Date.today().next().month();
You will have the exact value for today + 1 month (including days)
If you use moment.js, they have an add function.
Here's the link -
https://momentjs.com/docs/#/manipulating/add/
moment().add(7, 'months');
I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.
function addMonths(after = 1, now = new Date()) {
var current;
if (now.getMonth() == 11) {
current = new Date(now.getFullYear() + 1, 0, 1);
} else {
current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
}
Example
console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))
Output -
Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)
If you are able to get your hands on date-fns library v2+, you can import the function addMonths, and use that to get the next month
<script type="module">
import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm';
const nextMonth = addMonths(new Date(), 1);
console.log(`Next month is ${nextMonth}`);
</script>
ah, the beauty of ternaries:
const now = new Date();
const expiry = now.getMonth() == 11 ? new Date(now.getFullYear()+1, 0 , 1) : new Date(now.getFullYear(), now.getMonth() + 1, 1);
just a simpler version of the solution provided by #paxdiablo and #Tom
try this:
var a = screen.Data.getFullYear();
var m = screen.Data.getMonth();
var d = screen.Data.getDate();
m = m + 1;
screen.Data = new Date(a, m, d);
if (screen.Data.getDate() != d)
screen.Data = new Date(a, m + 1, 0);
You may probably do this way
var currentMonth = new Date().getMonth();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here
}
here is how i do it:
getMonthName(offset=0, format="long"){
/*
i.e.
offset: 0 - this month
offset: -1 - previous month
offset: 1 - next month
format: short - Oct
format: long - October
*/
const now = new Date();
const month = new Date(now.getFullYear(), now.getMonth() + offset, 1)
return month.toLocaleString('default', { month: format })
}
Related
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?
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.
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.
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);
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
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
A slight modification to solution provided by lebreeze:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
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.
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.
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)}
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);
This one works nicely:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
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
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);
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);
}
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);
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
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
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));
}
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);
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.
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())
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>
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));
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
In my case, this code was useful
end_date = new Date(2018, 3, 1).toISOString().split('T')[0]
console.log(end_date)
i am looking to display the date plus 1 month inside a div which will be used to display next invoice date. i have seen a few examples in various places, but could not implement. I also saw that there were many solutions, and some controversy surrounding each one.
Once you have a date object, just call setMonth(), passing in the current number of months plus 1.
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
You can either use this : http://jsfiddle.net/dfA8b/ if you need same date of the next month
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text(invoiceDt.toDateString());
Or
You can use this : http://jsfiddle.net/hjSDu/ if you need 30 days month(mostly used for invoice purposes)
var invoiceDt = new Date();
var days = 30;
invoiceDt.setDate(invoiceDt.getDate()+days);
$('#invoiceDate').text(invoiceDt.toDateString());
For the formatting purpose :
http://jsfiddle.net/7bU6n/
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text((invoiceDt.getMonth()+1) +"-"+ invoiceDt.getDate() +"-" + invoiceDt.getFullYear());
also see : https://stackoverflow.com/a/1643468/3603806
1 month is not so clear... what You mean? 31, 30 days or if exists simply same date of the following month?
1st case: (assuming 31 days)
var d = new Date(),
dplus31 = d.getDate() + 31;
d.setDate(dplus31);
console.debug(d, dplus31);
2nd case: one month
var d = new Date(),
dplus1 = d.getMonth() + 1;
d.setMonth(dplus1);
console.debug(d, dplus1);
..but even in this case there are some edge cases (ex. 31 January)
hope it helps
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.
So I am working on a Javascript calendar to reflect the current month along with the last few days of last month, and the first few days of the next month. I've ran into an issue I can't figure out for the life of me.
I have the following
var today = new Date();
var lastMonthDays = new Date(today.getFullYear(), today.getMonth() - 1, 0).getDate();
This should return the last day of the last month respectively, but it's giving me the value 31 which represents 31 days, however, in April there is only 30 days. So my best guess is that it's giving me the current months number of days. Shouldn't this be giving me 30? I've looked at other examples online and from what it looks like, what I have right now should work just fine.
No, it's giving you 31 because March has 31 days. Try this:
var lastMonthDays = new Date(today.getFullYear(), today.getMonth(), 0).getDate();
The 0 in the day-of-month field effectively means "the day before the 1st of this month".
today.getMonth() gives a zero-indexed month. i.e.
Jan: 0,
Feb: 1,
Mar: 2,
...
Therefore you don't need the -1 to get the previous month
var today = new Date();
var lastMonthDays = new Date(today.getFullYear(), today.getMonth(), 0).getDate();
A Date object’s getMonth() method seems to have a bug. Assuming the Date d is 2013-01-31, I attempt to set the month on d like this:
const d = new Date(); // 2013-01-31
d.setMonth(8);
console.log(d.getMonth());
The result is 9. Why? I tested this both in Chrome and Firefox.
I found out that when it’s the 31st, 30th, or 29th of a month, setting the date to a month that has a fewer number of days causes getMonth to return the wrong value.
Let's break this down:
var d = new Date(); // date is now 2013-01-31
d.setMonth(1); // date is now 2013-02-31, which is 3 days past 2013-02-28
x = d.getMonth(); // what to do, what to do, 3 days past 2013-02-28 is in March
// so, expect x to be March, which is 2
This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth(). Otherwise, it works as you'd expect.
The simplest solution to this is to add a second argument to setMonth:
var d = new Date();
d.setMonth(8,1);
d.getMonth(); //outputs 8
https://www.w3schools.com/jsref/jsref_setmonth.asp
Date.setMonth(month,day)
day: Optional. An integer representing the day of month
Expected values are 1-31, but other values are allowed:
0 will result in the last day of the previous month-1 will result in the day before the last day of the previous month
If the month has 31 days:
32 will result in the first day of the next month
If the month has 30 days:
32 will result in the second day of the next month
Months in JavaScript are represented from 0-11. Month 1 would be February which only has 28/29 days, so when you set the month to 1, it tries to auto-correct the date to March to make a date that makes sense (since Feb 31st, makes no sense). Try it out by using the toDateString function to see what I mean:
var d = new Date('2013/01/31');
d.setMonth(2);
console.log(d.toDateString()); // outputs Match 3rd, 2013
A little weird perhaps, but not buggy.
In javascript month is start from 0. Assume today is 02/04/2012, when you setMonth(1) it will try to set to feb. Since max day in feb is 28/29, it move to the next month (March, which is 2)
The setMonth here is not what you expect, and what happens in better libraries.
If you set a date 31.x.yyyy to x+1, probably the next month (x+1) will not have 31 days. So 31.x+1.yyyy will be changed to 1.x+2.yyyy.
In such case, the month will be increased by 2 - the date completely changed.
I had this problem with changing February->March, thanks God that was only a test.
This has to do with the current local date, even if the date you're setting is in the past or future (assuming you are correctly using the month range 0-11). This is because when you initialize Date(), it is using the current date. When you modify the date by using setFullYear(), setMonth() or setDate(), the default "current" values are still present and can shift the date.
If your current day of the month (today) is the 31st of the month and you then set a date in the past using setMonth(), setDate() where the month has less than your current 31 days, then Date() will give you the wrong month, even if you specifically state it. This is because when you setMonth(), the current date value of 31, which doesn't exist in the month you set, pushes it into the next month. Then when you set the date, the month never changes back.
If you set the day of the month before the month - setDate(), setMonth(), this fixes the problem, but has another similar issue / bug. If your current month only has 30 days and the date you're trying to set has 31 days, it will set the date of the month as 1, not 31. This is resolved if you set the month before the day - setMonth(), setDate(), but then you're back to the first problem.
Solutions:
Get the values and then set the day of the month and month at the same time (as reetah suggested) - setMonth(8,1)
Set the year with optional values to initialize setFullYear(1972, 0, 1), then setMonth, setDate.
Set the month, set the day, then verify the month equals what you
set it to and set it again if not - setMonth(), setDate(), setMonth()
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
var date = new Date();
if (date.getDate() < 31) {
$("#mydate").text("YOUR LOCAL DATE (on your computer) MUST BE SET TO THE 31st for this bug to show.");
} else {
date.setFullYear(1972);
date.setMonth(8); // (month-1)
date.setDate(24);
var breakdown = "<br>Day: " + date.getDate() + "<br>Month: " + date.getMonth() + "<br>Year: " + date.getFullYear();
$("#mydate").html("Set as September (8)<br><br>" + formatDate(date) + breakdown);
var date = new Date();
date.setFullYear(1972);
date.setMonth(8, 24); // (month-1)
var breakdown = "<br>Day: " + date.getDate() + "<br>Month: " + date.getMonth() + "<br>Year: " + date.getFullYear();
$("#mydate4").html("Set as September (8) but set day before month<br><br>" + formatDate(date) + breakdown);
date.setFullYear(1972);
date.setMonth(9); //October (month-1)
date.setDate(24);
var breakdown = "<br>Day: " + date.getDate() + "<br>Month: " + date.getMonth() + "<br>Year: " + date.getFullYear();
$("#mydate2").html("Set as October (9)<br><br>" + formatDate(date) + breakdown);
var date = new Date();
date.setFullYear(1972);
date.setMonth(7); //Aug (month-1)
date.setDate(24);
var breakdown = "<br>Day: " + date.getDate() + "<br>Month: " + date.getMonth() + "<br>Year: " + date.getFullYear();
$("#mydate3").html("Set as August (7)<br><br>" + formatDate(date) + breakdown);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
September 1972 has only 30 days. If your current local day is 31, the Date will return October 1972 when you specify September before you specify the day of the month.
<br><br><div id="mydate" style="color: red;">
</div>
<br><br>
<div id="mydate4">
</div><br><br>
<div id="mydate2">
</div>
<br><br>
<div id="mydate3">
</div>
Well, from a standpoint of a consumer of setMonth() method I would expect it to behave logically and not overflow to a different calendar month. Setting the actual day in the setMonth() method also is not the best option since in major cases I wouldn't like to get a first day of the changed month.
Yet, having in mind the Javascript logic about dates this behavior takes place in numerous flows: any month with 31 days in case the setMonth() is executed for the 31st day of that month and changed month does not have this day then the actual month as a result will not be the expected one.
Therefore I came up with the following solution that does cover all of the possible cases and results in the most close result to the desired one. I.e. setting a month for 31st day to a month that does not have it will set the month correctly and the day will be the last day of that month. This will work for all occasions (for instance for months with 30 and 29 days and the desired month of February).
Here's my solution in case anyone is interested:
public static addMonths(date: Date, value: number): Date {
let expectedMonth: number = date.getMonth() + value;
if (expectedMonth > 12) {
expectedMonth = expectedMonth % 12;
}
if (expectedMonth < 0) {
expectedMonth += 12;
}
date.setMonth(date.getMonth() + value);
const daysToAdd: number = date.getMonth() > expectedMonth ? -1 : 1;
while (date.getMonth() !== expectedMonth) {
date.setDate(date.getDate() + daysToAdd);
}
return date;
}
I just resolved this way:
Example
var d = new Date('2013/01/31');
m = d.getMonth();
month = m*100/100 + 1;
Var month contains the correct value.
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?
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.
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.
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);
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
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
A slight modification to solution provided by lebreeze:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
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.
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.
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)}
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);
This one works nicely:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
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
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);
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);
}
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);
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
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
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));
}
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);
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.
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())
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>
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));
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
In my case, this code was useful
end_date = new Date(2018, 3, 1).toISOString().split('T')[0]
console.log(end_date)