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


当前回答

我知道,但有时我喜欢这样:

function addDays(days) {
    return new Date(Date.now() + 864e5 * days);
}

其他回答

短:

函数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提供的修复程序

我总结了小时和天。。。

Date.prototype.addDays = function(days){
    days = parseInt(days, 10)
    this.setDate(this.getUTCDate() + days);
    return this;
}

Date.prototype.addHours = function(hrs){
    var hr = this.getUTCHours() + parseInt(hrs  , 10);
    while(hr > 24){
      hr = hr - 24;
      this.addDays(1);
    }

    this.setHours(hr);
    return this;
}

为管道运营商设计的解决方案:

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库。

已缩小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>

这些答案让我感到困惑,我更喜欢:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime()给出了自1970年以来的毫秒数,86400000是一天中的毫秒数。因此,ms包含所需日期的毫秒。

使用毫秒构造函数可以得到所需的日期对象。