Touhami
Touhami

Reputation: 809

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;

Upvotes: 1

Views: 364

Answers (2)

retype
retype

Reputation: 2385

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.

Upvotes: 1

rhgb
rhgb

Reputation: 4205

I've written some code for this sometime ago:

Date.prototype.getMonday=function(){return this.getDay()==1 ? this.clone().clearTime() : this.clone().prev().monday().clearTime();};
// This function returns the Monday of current week
var today=new Date();
today.getMonday().toString();
today.getMonday().next().sunday().toString();
// start and end of this week
today.getMonday().prev().monday().toString();
today.getMonday().prev().day().toString();
// previous week
today.getMonday().next().monday().toString();
today().getMonday().next().sunday().sunday().toString();
// next week

May these help.

Upvotes: 1

Related Questions