1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Ey, thanks for the advice. We use moment in our product but only when its need to show dates well-formated. In other case we prefer don't use libraries if it can be done with standard without add complexity. PD: Nice library!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.