Add days to JavaScript Date

2018-12-31 00:57发布

How to add days to current Date using JavaScript. Does JavaScript have a built in function like .Net's AddDay?

30条回答
高级女魔头
2楼-- · 2018-12-31 01:12

The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

setDate()

  • Sets the day of the month (1-31) for a specified date according to local time.

That is why I use setTime() when I need to add days.

查看更多
美炸的是我
3楼-- · 2018-12-31 01:13

No, javascript has no a built in function, but you can use a simple line of code

timeObject.setDate(timeObject.getDate() + countOfDays);
查看更多
人间绝色
4楼-- · 2018-12-31 01:13

Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.

const newDate = DateFns.addDays(oldDate, 2);
查看更多
永恒的永恒
5楼-- · 2018-12-31 01:14

I am using the following solution.

var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);

Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.

What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.

查看更多
余生无你
6楼-- · 2018-12-31 01:15

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.

If you want to just simply add n days to the date you have you are best to just go:

myDate.setDate(myDate.getDate() + n);

or the longwinded version

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.

查看更多
高级女魔头
7楼-- · 2018-12-31 01:18

I had issues with daylight savings time with the proposed solution.

By using getUTCDate / setUTCDate instead, I solved my issue.

// Curried, so that I can create helper functions like `add1Day`
const addDays = num => date => {
  // Make a working copy so we don't mutate the supplied date.
  const d = new Date(date);

  d.setUTCDate(d.getUTCDate() + num);

  return d;
}
查看更多
登录 后发表回答