user3247413
user3247413

Reputation: 11

javascript how to get next week's date, and compare dates

I am new to javascript. I wonder if there's any built-in methods that I could use.

For example, given today is May 8 2014, I want my cell to show 'May 8 2014 - May 15 2014' In same month, I can just add the date by 7, but what about 'May 28 2014 - June 4 2014'? And how do I compare two dates? And how do I tell if a date is within that week period?

Thanks for any ideas.

Upvotes: 1

Views: 3903

Answers (1)

Stefano Dalpiaz
Stefano Dalpiaz

Reputation: 1673

If you use the setDate function, it will add the number of days that you want, and you will not have to worry about changing month or year, it will done automatically. To compare dates, you can simply use the > and < operators as you would do with any number (actually under the hood, a Date in Javascript is a number).

Example:

var now = new Date();

var nextWeek = new Date(now);
nextWeek.setDate(nextWeek.getDate() + 7);

var tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);

if (tomorrow > now && tomorrow < nextWeek)
    alert('All good!');

Upvotes: 7

Related Questions