如何使用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())

其他回答

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

小心,因为这可能很棘手。当设置明天时,它仅在当前值与今天的年份和月份匹配时有效。然而,通常将日期设置为“32”这样的数字仍然可以很好地将其移动到下一个月。

您可以使用以下选项创建一个:-

Date.prototype.addDays=函数(天){var date=新日期(this.valueOf());date.setDate(date.getDate()+天);返回日期;}var date=新日期();console.log(date.addDays(5));

这会在必要时自动增加月份。例如:

8/31+1天将变为9/1。

直接使用setDate的问题是它是一个赋值函数,最好避免这种情况。ECMA认为将Date视为一个可变的类而不是一个不可变的结构是合适的。

我已经用这种方法在一行中找到了正确的日期,以获得时间加上人们上面所说的一天。

((new Date()).setDate((new Date()).getDate()+1))

我只是想建立一个正常的(新日期()):

(new Date()).getDate()
> 21

使用上面的代码,我现在可以在(newDate())中的Date()中设置所有这些,并且它的行为正常。

(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22

或获取Date对象:

(new Date(((new Date()).setDate((new Date()).getDate()+1))))

不,javascript没有内置函数,但是您可以使用一行简单的代码

timeObject.setDate(timeObject.getDate() + countOfDays);

我实现的最简单的方法是使用Date()本身。`

const days = 15; 
// Date.now() gives the epoch date value (in milliseconds) of current date 
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)

`