Search code examples
javascriptdatejs

Datejs calculate next and prev days in week


i use datejs and i want to get programme three buttons,
Today : generate two dates limites of this week, the monday and the sunday of thise week
Next : generate two dates limites of the next week
Prev : generate two dates limites of the prev week

here my code

var currentDay = 0;
(currentDay).days().fromNow().next().saturday().toString("yyyy-M-d");

(currentDay).days().fromNow().prev().monday().toString("yyyy-M-d");

the three buttons do currentDay + 7; currentDay - 7; currentDay = 0;

the probléme is
we are monday 22, and this function return me the monday 15;


Solution

  • The following sample .getWeekRange() function accepts a Date object (or defaults to 'today'), will figure out the Monday of that week, then returns an object with a start and end property for the week.

    Example

    var getWeekRange = function (date) {
        var date = date || Date.today(),
            start = date.is().monday() ? date : date.last().monday(),
            end = start.clone().next().sunday();
    
        return {
            start  : start,
            end : end
        };
    };
    

    You can then use the function to acquire the week range for any given Date:

    Example

    var range = getWeekRange();
    
    console.log("Start", range.start);
    console.log("End", range.end);
    

    To get the previous week, just pass in a Date object from the previous week:

    Example

    var prev = getWeekRange(Date.today().last().week());
    

    To get the next week, just pass in a Date object from the next week:

    Example

    var next = getWeekRange(Date.today().next().week());
    

    Hope this helps.