如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
date d = new Date() // current date
date tomorrow = d.setMonth(d.getMonth(),d.getDate()+1) // return a date incremented by 0 months and 1 day
其他回答
最简单的答案是,假设需要在当前日期上增加1天:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
要逐行向您解释此代码的作用:
创建名为currentDate的当前日期变量。默认情况下,“new Date()”会自动将当前日期分配给变量。创建一个变量以保存要添加到日期的天数(您可以跳过此变量,直接使用第三行中的值)通过给定相同的值+所需的数字来更改Date的值(因为Date是保存在对象中的月份的日期)。切换到下个月将是自动的
我对所提出的解决方案的夏令时有问题。
通过改用getUTCDate/setUTCDate,我解决了问题。
// 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;
}
用javascript扩展原型可能不是一个好主意,尤其是在专业代码库中。
您要做的是扩展本机Date类:
类MyCustomDate扩展日期{addDays(天){const date=新的MyCustomDate(this.valueOf());date.setDate(date.getDate()+天);返回日期;}}const today=新的MyCustomDate();const nextWeek=today.addDays(7)console.log(下一周)
这样,如果有一天Javascript实现了一个原生的addDays方法,你就不会破坏任何东西。
我的测试示例可以在日期对象的同一实例中执行减号。
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())
为管道运营商设计的解决方案:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
用法:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
如果您需要更多功能,我建议查看日期fns库。