如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?


当前回答

我的测试示例可以在日期对象的同一实例中执行减号。

Date.prototype.reset=函数(){let newDate=新日期(this.timeStamp)this.setFullYear(newDate.getFullYear)this.setMonth(newDate.getMonth())this.setDate(newDate.getDate())this.setHours(newDate.getHours())this.set分钟(newDate.getMinutes())this.setSeconds(newDate.getSeconds())this.set毫秒(newDate.getMilliseconds())}Date.prototype.addDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))this.timeStamp=this.timeStamp+天毫秒this.reset()}Date.prototype.minusDays=函数(天){this.timeStamp=此[Symbol.toPrimitive]('编号')let daysInMiliseconds=(天*(1000*60*60*24))如果(daysInMiliseconds<=this.timeStamp){this.timeStamp=this.timeStamp-天毫秒this.reset()}}var temp=新日期(Date.now())//从现在开始console.log(temp.toDateString())临时添加天数(31)console.log(temp.toDateString())温度-天(5)console.log(temp.toDateString())

其他回答

我使用的是:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

节省时间的工作:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

与新年一起工作:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

它可以参数化:

function DateAdd(source, amount, step) {
  var factor = 1;
  if (step == "day") factor = 24 * 60 * 60 * 1000;
  else if (step == "hour") factor = 60 * 60 * 1000;
  ...
  new Date(source.getTime() + amount * factor);
}

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js

console.log(clock.wwhat.wayday(clock.now+clock.unit.days))//“星期三”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*2))//“星期四”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*3))//“星期五”<script src=“https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js“></script>

编辑:您可以这样做,而不是setTime()(或setHours()):

Date.prototype.addDays= function(d){
  this.setDate(this.getDate() + d);
  return this;
};

var tomorrow = new Date().addDays(1);

Old:

可以使用setHours()代替setTime():

Date.prototype.addDays= function(d){
    this.setHours(this.getHours() + d * 24);
    return this;
};

var tomorrow = new Date().addDays(1);

查看JSFiddle。。。

最简单的答案是,假设需要在当前日期上增加1天:

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

要逐行向您解释此代码的作用:

创建名为currentDate的当前日期变量。默认情况下,“new Date()”会自动将当前日期分配给变量。创建一个变量以保存要添加到日期的天数(您可以跳过此变量,直接使用第三行中的值)通过给定相同的值+所需的数字来更改Date的值(因为Date是保存在对象中的月份的日期)。切换到下个月将是自动的

这些答案让我感到困惑,我更喜欢:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。

使用毫秒构造函数可以得到所需的日期对象。