How to add number of days to today's date? [du

2018-12-31 03:30发布

This question already has an answer here:

I need to be able to add 1, 2 , 5 or 10 days to today's date using jQuery.

16条回答
心情的温度
2楼-- · 2018-12-31 04:27

You could extend the javascript Date object like this

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

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);
查看更多
浪荡孟婆
3楼-- · 2018-12-31 04:28

If the times in the Date are not needed, then you can simply use the date object's methods to extract the Month,Year and Day and add "n" number of days to the Day part.

var n=5; //number of days to add. 
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)

Ref:Mozilla Javascript GetDate

Edit: Ref: Mozilla JavaScript Date

查看更多
不流泪的眼
4楼-- · 2018-12-31 04:30

The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)

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

Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().

查看更多
孤独总比滥情好
5楼-- · 2018-12-31 04:30

you can try this and don't need JQuery: timeSolver.js

For example, add 5 day on today:

var newDay = timeSolver.add(new Date(),5,"day");

You also can add by hour, month...etc. please see for more infomation.

查看更多
登录 后发表回答