Как я могу добавить 1 день к текущей дате?

93

У меня есть текущий объект Date, который нужно увеличить на один день с помощью объекта Date JavaScript. У меня есть следующий код:

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.

franticfrantic
источник
1
What do you mean by "add +1"? Do you need the next day or something else?
Aleks G
Does date: (date.getUTCDate()+1) not work (works for me)? It's possible that there is a naming conflict with date (as Date()-Object and as Object-Key. Have you tried calling the Date()-Object different?
Dominik Schreiber
currently it show up only as: <option value="2012-04-06">Sat 6 Apr 2012</option><option value="2012-04-07"> 7 Apr 2012</option>, no "Sunday 7 Apr 2012"
franticfrantic
So it's not the 7 Apr you need (what is 'add next day' to me), it's the Sunday. Remember to add the +1 both in day: and date: (or, as the current answer mentions, before).
Dominik Schreiber

Ответы:

237

To add one day to a date object:

var date = new Date();

// add a day
date.setDate(date.getDate() + 1);
RobG
источник
See duplicate question: stackoverflow.com/questions/3674539/…. This answer is good, but does not account for DST. There are 2 days of the year that do not have 24 hours.
Jess
2
@Jess—it depends on how you want changes over DST represented. The question asked how to add one to the date, that's exactly what the above answer does. Adding 24 hours doesn't necessarily increment that date, adding one to the local date using setDate always does.
RobG
Here is what I mean. Incrementing March 10: var a = new Date("2013-03-10T00:00:00.000Z"); a.setDate(a.getDate() + 1); a.toISOString(); is "2013-03-10T23:00:00.000Z". This is a subtle case where the above function did not work for me.
Jess
1
Of course not! You start with a UTC time, then essentially convert it to local, add a day, then convert it back to UTC. So one day was added to the local date, but only 23 hrs the UTC time. If you add 1 to the UTC date, you'll get back 01:00:00 local time. That behaviour isn't unique to daylight saving, it's a consequence of using three different timezones.
RobG
8
Aha. I didn't realize getDate was converting from UTC to local time. a.setUTCDate(a.getUTCDate() + 1); <-- that works with Zulu dates.
Jess
40

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 your 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();

imo this insures accuracy

here is another example i Do not like that can work for you but not as clean that dose the 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 Im 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 dose 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.
Peter the Russian
источник
Adding seconds/milliseconds won't work for daylight savings.
Matt H
@Matt H where did you get that idea from. The time is set in UTC in milliseconds from 1970/01/01
Peter the Russian
1
It will be the following day in UTC time, yes, but not necessarily in local time. On Spring Forward day in the US, there are 25 hours in the day. So if you have e.g. 3/31/15 at 00:00 hours, and add 86400000 milliseconds, on Sprint Forward day, the local time would be 3/31/15 at 23:00 hours since there are 25 hours in that day.
Matt H
3
you can see the effect like this: var dte = Date.parse('2015-11-01'); console.log(dte); dte.setTime(dte.getTime() + 86400000 ); console.log(dte);
Matt H
1
This is over-engineered. If you're having a problem like this use a library like moment or something to help make things easier.
Joshua Michael Waggoner
11

If you want add a day (24 hours) to current datetime you can add milliseconds like this:

new Date(Date.now() + ( 3600 * 1000 * 24))
Pablo Andres Diaz Mazzaro
источник
9
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);

Serge
источник
Adding one day of milliseconds fails because not all days are 24 hours long in places that observe daylight saving. E.g. Chile ends daylight saving at midnight on the start of 14 May 2017. Clocks will wind back from midnight to 23:00. So adding 24 hours to 2017-05-13 00:00:00 will produce 2017-05-13 23:00:00, and the date doesn't change (some browsers will do it at exactly midnight, others one millisecond after). :-(
RobG
2

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

Jee Mok
источник
-3
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');
Paul Wolbers
источник
What is this? Are you using a library?
remborg