JavaScript, get date of the next day

JavascriptDate

Javascript Problem Overview


I have the following script which returns the next day:

function today(i)
	{
		var today = new Date();
		var dd = today.getDate()+1;
		var mm = today.getMonth()+1;
		var yyyy = today.getFullYear();
		
		today = dd+'/'+mm+'/'+yyyy;

		return today;	
	}

By using this:

today.getDate()+1;

I am getting the next day of the month (for example today would get 16).

My problem is that this could be on the last day of the month, and therefore end up returning 32/4/2014

Is there a way I can get the guaranteed correct date for the next day?

Javascript Solutions


Solution 1 - Javascript

You can use:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Solution 2 - Javascript

Copy-pasted from here: https://stackoverflow.com/questions/3674539/javascript-date-increment-question

> Three options for you: > > Using just JavaScript's Date object (no libraries): > > var today = new Date(); > var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); >

One-liner

> const tomorrow = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating > a new date): > > var dt = new Date(); > dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000)); > > Edit: See also Jigar's answer and David's comment below: var tomorrow > = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); > > Using MomentJS: > > var today = moment(); > var tomorrow = moment(today).add(1, 'days'); > > (Beware that add modifies the instance you call it on, rather than > returning a new instance, so today.add(1, 'days') would modify today. > That's why we start with a cloning op on var tomorrow = ....) > > Using DateJS, but it hasn't been updated in a long time: > > var today = new Date(); // Or Date.today() > var tomorrow = today.add(1).day();

Solution 3 - Javascript

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

> Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam MossView Question on Stackoverflow
Solution 1 - JavascriptacarlonView Answer on Stackoverflow
Solution 2 - JavascriptRuslan F.View Answer on Stackoverflow
Solution 3 - JavascriptloxxyView Answer on Stackoverflow