I was just creating a simple calendar when users clicks next it gets the following day, very simple code:

var dateSelected = new Date('02/06/2013'); //any date 
var day = new Date(dateSelected.getTime() + 24*60*60*1000);
alert(day.getDate());

that works great for all dates but for some reason it doesn't get the next day when the date is 27 Oct 2013

var dateSelected = new Date('10/27/2013');

I don't seem to be able to figure out why, if I go manually to the next day 28 Oct it keeps working fine.

Any ideas why this happens?

UPDATE: I fixed it by adding the time as well as the date:

var dateSelected = new Date('10/27/2013 12:00:00');
有帮助吗?

解决方案

I strongly suspect this is because of your time zone - which we don't know, unfortunately.

On October 27th 2013, many time zones "fall back" an hour - which means the day is effectively 25 hours long. Thus, adding 24 hours to your original value doesn't change day if it started within the first hour of the day.

Fundamentally, you need to work out whether you're actually trying to add a day or add 24 hours - they're not the same thing. You also need to work out which time zone you're interested in. Unfortunately I don't know much about Javascripts date/time API, but this is almost certainly the cause of the problem.

其他提示

Rather than adding the number of milliseconds in a day, you can use the set date function directly.

var dateSelected = new Date('10/27/2013');
var daysToAdd = 1;

var nextDay = new Date(dateSelected.getTime());
nextDay.setDate(dateSelected.getDate() + daysToAdd);

This also works when rolling over to the next month, and should work well with different time zones.

As Jon Skeet already mentioned, the problem results from your local timezone. As a possible solution, you can use the setDate and getDate functions of the Date object:

var dateSelected = new Date('02/06/2013'); //any date 
dateSelected.setDate(dateSelected.getDate() + 1);
alert(dateSelected.getDate());

And of course, no JavaScript Date question could be complete without a Moment.js answer:

var m = moment('10/27/2013','MM/DD/YYYY').add('days', 1);

Superior API every time. :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top