如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
我试图解决类似的问题,我更喜欢getTime方法,但有一些奇怪的基于时区的副作用。
ofc将“今天”替换为您需要的任何日期,并将时间也输入。关键是获取UTC时间,然后用毫秒来做加法,以避免这些副作用。
var now = new Date(Date.now());
var today = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
const dayInMs = 86400000; //24 hours
const tomorrow = new Date(today.getTime() + dayInMs);
其他回答
我实现的最简单的方法是使用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)
`
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
小心,因为这可能很棘手。当设置明天时,它仅在当前值与今天的年份和月份匹配时有效。然而,通常将日期设置为“32”这样的数字仍然可以很好地将其移动到下一个月。
我的测试示例可以在日期对象的同一实例中执行减号。
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 ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。
使用毫秒构造函数可以得到所需的日期对象。
试试这个
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
推荐文章
- 在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编写的函数吗?