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


当前回答

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js

console.log(clock.wwhat.wayday(clock.now+clock.unit.days))//“星期三”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*2))//“星期四”console.log(clock.wwhat.wayday(clock.now+(clock.unit.days*3))//“星期五”<script src=“https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js“></script>

其他回答

setDate()的mozilla文档并不表示它将处理月末场景。看见https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

设置日期()

根据当地时间设置指定日期的月份日期(1-31)。

这就是我在需要添加天数时使用setTime()的原因。

短:

函数addDays(日期,数字){const newDate=新日期(日期);返回新日期(newDate.setDate(newDate.getDate()+number));}控制台日志({明天:addDays(新日期(),1)});

预付款:

函数addDays(日期,数字){const newDate=新日期(日期);返回新日期(newDate.setDate(Date.getDate()+number));}函数addMonths(日期,数字){const newDate=新日期(日期);返回新日期(newDate.setMonth(newDate.getMonth()+number));}函数addYears(日期,数字){const newDate=新日期(日期);返回新日期(newDate.setFullYear(newDate.getFullYear)+number);}函数getNewDate(dateTime){let date=新日期();let number=parseInt(dateTime.match(/\d+/)[0]);if(dateTime.indexOf('-')!=-1)number=(-number);如果(dateTime.indexOf('day')!=-1)date=addDays(日期,数字);否则如果(dateTime.indexOf('month')!=-1)date=addMonths(日期,数字);否则如果(dateTime.indexOf('year')!=-1)date=addYears(日期,数字);返回日期;}控制台日志({明天:获取新日期(“+1天”),昨天:getNewDate('-1day'),nextMonth:getNewDate(“+1个月”),nextYear:getNewDate(“+1年”),});

使用jperl提供的修复程序

我试图解决类似的问题,我更喜欢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);    

以下是在Javascript中为特定日期添加日期、月份和年份的方法。

// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);

// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);

// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);

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

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