Shinigami
Shinigami

Reputation: 1055

JQuery how pick the Monday of the week of the picked day

I use Datepicker JQuery and I need to select the monday of the weeks of the day that the user picks. i.e.

The user picks 13th of march 2013(Wednesday). so I'd like to pick 11th of march 2013(monday).

I hope I'm clear. Tnx

Upvotes: 0

Views: 189

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44685

I would do this solely in JavaScript. You can get the weekday from a specific given date by using getWeekDay(). That also means you can get the difference (in days) between the day from the picked date and monday of that week.

Then you can subtract the difference in days by setting a new timestamp. This means you need to get the milliseconds between the picked day and monday of that week which you can get by multiplying the number of days with 24 (to get it in hours), then with 60 (minutes), another 60 to get the seconds and finally 1000 to get it in milliseconds.

The result would be something like:

function getMonday(/** Date */ date) {
    var diff = (date.getDay() == 0 ? 6 : date.getDay() - 1);
    date.setTime(date.getTime() - (diff * 24 * 60 * 60 * 1000));
    return date;
}

I also wrote a JSFiddle to test it.

Upvotes: 1

Related Questions