如何使用JavaScript将日期添加到当前日期?JavaScript是否有像.NET的AddDay()那样的内置函数?
当前回答
这类函数有问题,我用parseInt()解决
Date.prototype.addDays = function(dias) {
var date = new Date(this.valueOf());
date.setDate(parseInt(date.getDate()) + parseInt(dias));
return date;
}
Date.prototype.addMonths = function(months) {
var date = new Date(this.valueOf());
date.setMonth(parseInt(date.getMonth()) + parseInt(months));
return date;
}
Date.prototype.addYears = function(years) {
var date = new Date(this.valueOf());
date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
return date;
}
其他回答
试试这个
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
减去30天使用(24小时=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=新日期();var d=新日期(+yourDate-30*86400000)控制台日志(d)
您可以使用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;
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
小心,因为这可能很棘手。当设置明天时,它仅在当前值与今天的年份和月份匹配时有效。然而,通常将日期设置为“32”这样的数字仍然可以很好地将其移动到下一个月。