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


当前回答

最简单的解决方案。

Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);

其他回答

完成此操作的最简单方法是使用日期fns库。

var addDays = require('date-fns/add_days')
addDays(date, amount)

此链接中提供了文档。您也可以使用moment.js完成此操作

希望它有帮助!

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

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

我的简单解决方案是:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

这种解决方案在夏时制方面没有问题。此外,还可以添加/减去年、月、日等的任何抵销。

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

是正确的代码。

最简单的解决方案。

Date.prototype.addDays=函数(天){this.setDate(this.getDate()+parseInt(天));返回此;};//然后打电话var newDate=新日期().addDays(2)//+2天console.log(newDate);//或var newDate1=新日期().addDays(-2)//-2天console.log(newDate1);

我正在使用以下解决方案。

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有一个接受int的构造函数。此参数表示1970年1月1日之前/之后的总毫秒数。它还有一个方法setTime,该方法在不创建新的Date对象的情况下执行同样的操作。

我们在这里做的是将天数转换为毫秒,并将该值添加到getTime提供的值中。最后,我们将结果提供给Date(毫秒)构造函数或setTime(毫秒)方法。