如何使用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

其他回答

我昨晚创建了这些扩展:可以传递正值或负值;

例子:

var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);


Date.prototype.addDays = function (num) {
    var value = this.valueOf();
    value += 86400000 * num;
    return new Date(value);
}

Date.prototype.addSeconds = function (num) {
    var value = this.valueOf();
    value += 1000 * num;
    return new Date(value);
}

Date.prototype.addMinutes = function (num) {
    var value = this.valueOf();
    value += 60000 * num;
    return new Date(value);
}

Date.prototype.addHours = function (num) {
    var value = this.valueOf();
    value += 3600000 * num;
    return new Date(value);
}

Date.prototype.addMonths = function (num) {
    var value = new Date(this.valueOf());

    var mo = this.getMonth();
    var yr = this.getYear();

    mo = (mo + num) % 12;
    if (0 > mo) {
        yr += (this.getMonth() + num - mo - 12) / 12;
        mo += 12;
    }
    else
        yr += ((this.getMonth() + num - mo) / 12);

    value.setMonth(mo);
    value.setYear(yr);
    return value;
}

减去30天使用(24小时=86400000ms)

new Date(+yourDate - 30 *86400000)

var yourDate=新日期();var d=新日期(+yourDate-30*86400000)控制台日志(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方法,你就不会破坏任何东西。

我使用的是:

new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)

节省时间的工作:

new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

与新年一起工作:

new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)

它可以参数化:

function DateAdd(source, amount, step) {
  var factor = 1;
  if (step == "day") factor = 24 * 60 * 60 * 1000;
  else if (step == "hour") factor = 60 * 60 * 1000;
  ...
  new Date(source.getTime() + amount * factor);
}

您可以使用JavaScript,不需要jQuery:

var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 
Formatting to dd/mm/yyyy :

var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();

var someFormattedDate = dd + '/'+ mm + '/'+ y;