javascript date object :Error while using addDays function
I was trying to execute the below code in my javascript and got some exception
var now3 = new Date();
now3.addDays(-开发者_JAVA技巧4);
Error throwed is Microsoft JScript runtime error: Object doesn't support this property or method
I m using jQuery 1.3.2 in my page .
Whats wrong with this? Please help
There is no addDays()
method - you need to use setDate()
:
now3.setDate(now3.getDate() - 4);
See the Date object documentation for more information.
Well, you could add the addDays to the Date prototype:
Date.prototype.addDays = function(days) {
this.setDate( this.getDate() + days);
return this;
};
This should work fine.
Greg's hint is the way to go. You can find more info on JavaScript date manipulations here: http://www.w3schools.com/js/js_obj_date.asp
now3.addDays(-4);
put this function
Date.prototype.addDays = function(s)
{
var targetDays = parseInt(s)
var thisYear = parseInt(this.getFullYear())
var thisDays = parseInt(this.getDate())
var thisMonth = parseInt(this.getMonth() + 1)
var currDays = thisDays;
var currMonth = thisMonth;
var currYear = thisYear;
var monthArr;
var nonleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// leap year
var leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if ((thisYear % 4) == 0) {
if ((thisYear % 100) == 0 && (thisYear % 400) != 0) { monthArr = nonleap; }
else { monthArr = leap; }
}
else { monthArr = nonleap; }
var daysCounter = 0;
var numDays = 0;
var monthDays = 0;
if( targetDays < 0) {
while(daysCounter < (targetDays * -1) ) {
if(daysCounter == 0) {
if((targetDays * -1) < thisDays) {
break;
} else {
daysCounter = thisDays;
}
}else {
numDays = monthArr[currMonth - 1];
daysCounter += parseInt(numDays)
}
if(daysCounter > (targetDays * -1) ) {
break;
}
currMonth = currMonth - 1;
if(currMonth == 0) {
currYear = currYear - 1;
if ((currYear % 4) == 0) {
if ((currYear % 100) == 0 && (currYear % 400) != 0) { monthArr = nonleap; }
else { monthArr = leap; }
}
else { monthArr = nonleap; }
currMonth = 12;
}
}
t = this.getTime();
t += (targetDays * 86400000);
this.setTime(t)
var thisDate = new Date(currYear,currMonth - 1,this.getDate())
return thisDate;
} else {
var diffDays = monthArr[currMonth - 1] - thisDays;
numDays = 0;
var startedC = true;
while(daysCounter < targetDays ) {
if(daysCounter == 0 && startedC == true) {
monthDays = thisDays;
startedC = false;
}else {
monthDays++;
daysCounter++;
if(monthDays > monthArr[currMonth - 1]){
currMonth = currMonth + 1;
monthDays = 1;
}
}
if(daysCounter > targetDays) {
break;
}
if(currMonth == 13) {
currYear = currYear + 1;
if ((currYear % 4) == 0) {
if ((currYear % 100) == 0 && (currYear % 400) != 0) { monthArr = nonleap; }
else { monthArr = leap; }
}
else { monthArr = nonleap; }
currMonth = 1;
}
}
var thisDate = new Date(currYear,currMonth - 1,monthDays)
return thisDate;
}
}
精彩评论