Reputation: 159
I am having an issue and was wondering if someone could give me a little insight as to why. The following code is working to add one week to a date:
while (c.getStamp() < b.getStamp()) {
var f = this.getWeek(c);
e.push(f);
c = (c.getStamp() + 604800).toDate();
}
...
Date.prototype.getStamp = function() {
return Math.round(this.getTime() / 1e3);
};
Number.prototype.toDate = function() {
return new Date(this * 1e3);
};
I'm trying to get the following to work but it creates a continuous loop:
while (c.getStamp() < b.getStamp()) {
var f = this.getWeek(c);
e.push(f);
c = new Date(c.getFullYear(), c.getMonth(), c.getDate + 7, 0, 0, 0);
}
Where c = JS Date, ie 05/01/12
and b = JS Date, ie 05/31/12
Upvotes: 2
Views: 1806
Reputation: 147363
To add a week to a date, the simplest method is to add 7 days:
var now = new Date();
// add one week exactly
now.setDate(now.getDate() + 7);
If you add the equivalent of 7*24hrs in milliseconds, you will be incorrect if the week crosses a daylight saving boundary. And the above is a bit clearer in the code.
In your code:
> while (c.getStamp() < b.getStamp()) {
if c
and d
are both date objects, then:
while (c < b) {
is more efficient, less error prone and less to write.
> var f = this.getWeek(c);
What is f
? What does f.getWeek
return?
> e.push(f);
> c = (c.getStamp() + 604800).toDate();
Presumably you want to add one week to c, so:
c.setDate(c.getDate() + 7);
Later...
> c = new Date(c.getFullYear(), c.getMonth(), c.getDate + 7, 0, 0, 0);
> --------------------------------------------------------^
You have a syntax error and have not zeroed the milliseconds. This seems like an even longer-winded way to a a week to c
, see above.
Where c = JS Date, ie 05/01/12 and b = JS Date, ie 05/31/12
Please note that this in an international forum, regional specific expressions should be avoided or explained if used. Are the above in the US–specific mm/dd/yyyy format? A more widely recognised format is dd/mm/yyyy or better to use an ISO8601 format: yyy-mm-dd (which should be supported natively by all browsers compliant with ES5, but they all aren't yet).
Oh, and the getStamp
and toDate
methods seem like attempts at rounding to the nearest second. You might try a function that does just that in one go:
Date.prototype.roundToSecond = function() {
this.setMilliseconds(this.getMilliseconds() > 499? 1000 : 0);
}
Upvotes: 3
Reputation: 5893
Kolink has the right answer, but you might also want to take a look at the Moment.js date library if your doing alot of work with manipulating dates and formatting them.
Upvotes: 0
Reputation: 324620
You missed the ()
after c.getDate
.
Aside from that, you can just do this:
c.setTime(c.getTime()+7*24*60*60*1000); // adds 1 week to the date
Upvotes: 5