JomsDev
JomsDev

Reputation: 116

Dates in javascript

I need some help with javascript dates. I have found a bug when I was working. I think that it has been solved but I don't know why.

We have a custom calendar with seven days each pages (monday-sunday). When you pick next (>) it add 7 days. The trouble was that in october 2015 (19-25) when you pressed next, it becomes a new week with days between 25-31 instead of 26-1 week.

This was the code that sum one week:

date = new Date( date.getTime() + num * 86400000 );`

And this is how I "fix" it:

date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + num);`

Now the picker is working, I suppose 86400000 are the milliseconds in a day but why it doesn't work for some days?

Thanks

Upvotes: 1

Views: 53

Answers (2)

jusopi
jusopi

Reputation: 6813

If I may make a recommendation: check out Moment.js. While it doesn't directly answer your question as to why you're encountering your issue (@Pointy's answer is right), it will make such calculations such as yours much simpler.

Instead of this:

date = new Date( date.getTime() + num * 86400000 );

You can do this:

date = moment().add(1, 'w').toDate()

...and I believe it will account for daylight savings time.

Upvotes: 0

Pointy
Pointy

Reputation: 413996

Late October in your locale is when Daylight Savings or "Summer" time ends. One of the days in that week is slightly shorter than other days.

The internals of the JavaScript runtime know about that, so adding days via the setDate() API gets the right answer.

Upvotes: 2

Related Questions