如何使用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())
其他回答
感谢Jason的回答,您的回答符合预期,这里是您的代码和AnthonyWJones的便捷格式的混合:
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
为什么这么复杂?
假设您将要添加的天数存储在一个名为days_to_add的变量中。
那么这个简短的应该做到:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
使用Date.now(),您可以获得实际的unix时间戳(以毫秒为单位),然后添加您想要添加的天数。一天为24h60min60s*1000ms=86400000 ms或864E5。
我们的团队认为date fns是这个领域最好的图书馆。它将日期视为不可变的(Moment.js可能永远不会采用不变性),速度更快,可以模块化加载。
const newDate = DateFns.addDays(oldDate, 2);
int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
代码笔
var天数=2;var newDate=新日期(Date.now()+天*24*60*60*1000);document.write(“今日:<em>”);document.write(new Date());document.write('</em><br/>新建:<strong>');document.write(newDate);
不使用第二个变量,您可以用接下来的x天替换7:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?