Add days to JavaScript Date

2018-12-31 00:57发布

How to add days to current Date using JavaScript. Does JavaScript have a built in function like .Net's AddDay?

30条回答
泛滥B
2楼-- · 2018-12-31 01:30

If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:

var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

Reference: http://momentjs.com/docs/#/manipulating/add/

查看更多
路过你的时光
3楼-- · 2018-12-31 01:31

You can use JavaScript, no jQuery required:

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;
查看更多
与风俱净
4楼-- · 2018-12-31 01:31
function addDays(n){
    var t = new Date();
    t.setDate(t.getDate() + n); 
    var month = "0"+(t.getMonth()+1);
    var date = "0"+t.getDate();
    month = month.slice(-2);
    date = date.slice(-2);
     var date = date +"/"+month +"/"+t.getFullYear();
    alert(date);
}

addDays(5);
查看更多
梦该遗忘
5楼-- · 2018-12-31 01:32

These answers seem confusing to me, I prefer:

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

getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day. Hence, ms contains milliseconds for the desired date.

Using the millisecond constructor gives the desired date object.

查看更多
浪荡孟婆
6楼-- · 2018-12-31 01:33

The simplest solution.

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

 // and then call

 var newDate = new Date().addDays(2); //+2 days
 console.log(newDate);

 // or

 var newDate1 = new Date().addDays(-2); //-2 days
 console.log(newDate1);

查看更多
步步皆殇っ
7楼-- · 2018-12-31 01:33

Very simple code to add days in date in java script.

var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);

查看更多
登录 后发表回答