简体   繁体   中英

Get next week's start and end date using pure javascript

I was using moment.js to calculate the next week start date and end date. but right now i have removed it because of some minification issue.

I am able to get this week's start and end date as follows,

var today = new Date; 
var first = today.getDate() - today.getDay(); 
(this.fromDate = new Date(today.setDate(first)));
(this.toDate  = new Date(today.setDate(last)));

how to find next week start and end date?

You can achieve this using getFullYear() , getMonth() and getDate() methods.

 function getWeekBegin() { var now = new Date(); var next = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(7 - now.getDay())); return next; } var firstDay = getWeekBegin(); console.log("First day: "+firstDay); var lastDay=firstDay.setDate(firstDay.getDate() + 6); console.log("Last day: "+new Date(lastDay)); 

Not 100% what your after, but if you modify this a little you should be able to figure out how

function test() {
    var today = new Date; 
    alert(getMonday(today));
}
function getMonday( date ) {
    date.setHours((24*7));
    var day = date.getDay() || 7;  
    if( day !== 1 ) 
        date.setHours(-24 * (day - 1)); 
    return date;
}

Just edited the answer, this should get you next mondays date

Just sum 7 days to the start of this week to get the start of the next week; to get the end of the week add 6 days to the start of the week.

 var date = new Date; var nextWeekStart = date.getDate() - date.getDay() + 7; var nextWeekFrom = new Date(date.setDate(nextWeekStart)); var nextWeekEnd = date.getDate() - date.getDay() + 6; var nextWeekTo = new Date(date.setDate(nextWeekEnd)); console.log('nextWeekFrom: ' + nextWeekFrom.toString()) console.log('nextWeekTo : ' + nextWeekTo.toString()) 

The following simplifies the code and provides some explanation. The setDate method modifies the date and returns the new time value, so it can be used to modify a date and create a copy in one go.

 // Get current date var d = new Date(); // Set to next Sunday and copy var startOfWeek = new Date(d.setDate(d.getDate() + 7 - d.getDay())); // Set to the following Saturday d.setDate(d.getDate() + 6); console.log('Start of week: ' + startOfWeek.toString()); console.log('End of week : ' + d.toString()); // The following shows the dates formatted and in the host default language // Support for toLocaleString options may be lacking though var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log('Start of week: ' + startOfWeek.toLocaleString(undefined, options)); console.log('End of week : ' + d.toLocaleString(undefined, options)); 

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