简体   繁体   中英

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.

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!');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM