Javascript adding days to a Date - javascript

Hi I am trying to create a variable today that is the current date today. I am trying to add 106 days to it which works successfully. Then I am trying to create a second variable today2 and subtract 31 days from the 'today' variable (current date + 106 -31). This part is not working. This is what it is giving me...
Thu Mar 28 11:52:21 EDT 2013
Tue Nov 27 11:52:21 EST 2012
The second line is not 31 days before the first line. Can someone help me correct this?
Feel free to play with my jsfiddle http://jsfiddle.net/fjhxW/
<div id="current"></div>
<div id="current2"></div>
<div id="current3"></div>
var today = new Date();
var today2 = new Date();
today.setDate(today.getDate() + 106);
today2.setDate(today.getDate() - 31);
var dd = today.getDate();
var mm = today.getMonth(); //January is 0!
var yy = today.getFullYear();
document.getElementById('current').innerHTML = today;
document.getElementById('current2').innerHTML = today2;

it's Xmas time so I give the answer just to copy/paste:
var oneDay = 24 * 60 * 60 * 1000, // 24h
today = new Date().getTime(), // in ms
firstDate,
secondDate;
firstDate = new Date(today + 106 * oneDay);
secondDate = new Date(firstDate.getTime() - 31 * oneDay);

try datejs:
Date.parse('t - 31 d'); // today - 31 days
Date.today().add(106).days().add(-31).days();

You cannot pass a negative number to setDate. setDate is used to set the date to set the absolute day, not relative days.
From the docs:
If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly. For example, if you use 0 for dayValue, the date will be set to the last day of the previous month.

A mathemathical solution:
Add 75 days to your current day (106 - 31), then add 31 days to that date. Change the order in what you are showing both dates on your code.
Why go forward and backward when you can always go forward?

Related

End of Month using javascript [duplicate]

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)

Calculate Date with start date and number of days with javascript

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange results, but only on one date, I have been a few days now trying to figure this one out.
The function is:
CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var policy_start_date_add = new Date(policy_start_date.getTime() + ((days-1) * 24 * 60 * 60 * 1000));
var dateString = ("0" + (policy_start_date_add.getDate())).slice(-2) + "-" + ("0" + (policy_start_date_add.getMonth()+1)).slice(-2) + "-" + policy_start_date_add.getFullYear();
return dateString;}
The thing is it works until I use the date "28-10-2012" it gives me back the same date even if I add 2 days.
Any ideas, I am stumped.
Likely your local timezone changes because of the end of the daylight saving time.
> new Date(2012, 9, 28)
Sun Oct 28 2012 00:00:00 GMT+0200
> // 48 hours later:
> new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
Mon Oct 29 2012 23:00:00 GMT+0100
Always use the UTC methods!
BTW, adding days is much more easier with setDate, which also works around timezone issues:
function calculateDateFromDays(startDate, days) {
var datestrings = startDate.split("-"),
date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
date.setDate(date.getDate() + days);
return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
}
On October 28th the time changes from DST to "normal", so the day is not equal 24h. That may cause issues in your code.
Also why (days-1) * 24 * 60 * 60 * 1000? If you set days to 1 the whole expression evaluates to zero...
There's an easier way to achieve that :
http://jsfiddle.net/pjambet/wZEFe/2/
Use javascript date format:
How to format a JavaScript date
So you don't have to manually try to parse date strings.

How can I add 1 day to current date?

I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

How to find the next 4 days from the current day using javascript

I found the current day as Mar 27 2012 ....
var currentday = currentday.format("mmm d yyyy");
I want to find the add three days with this value.
i.e. i need the output as Mar 30 2012.
I also need to find the starting and ending date of a calendar. i.e. Feb 26 2012 - Mar 31 2012 to display the current month as displaying in calendar month view.
Can any one help me on this please....
var currentday = new Date();
var nextDay = new Date();
nextDay.setDate(currentday.getDate() + 4);
//Set number of days you want to compute to
var days=4;
//Get current date or whatever date you want to compute from
var currentDate=new Date();
var nDaysFromNow=new Date();
nDaysFromNow.setDate(currentDate.getDate()+days);
You can add days using the getDate() function like so:
var someDate = new Date();
someDate = someDate.getDate() + 3;
See code below.. Hope it helps
var days = 4;
var next = new Date((new Date).getTime() + ((1000*3600*24) *days));

Calculate last day of month

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)

Categories

Resources