Reputation: 5166
I am very weak with browser end script like javascript , as i am a php developer. I need to get the dates on Saturday and Sunday. I have found many answer to calculate the count but have not found a way to get dates on Saturday and Sunday .I have try these:
Date.prototype.endOfWeek = function(){
return new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() + 6 - this.getDay()
);
};
var now = new Date();
// returns next saturday; and returns saturday if it is saturday today.
alert(now.endOfWeek() );
it returns me only the next saturday date .Please help me to get this
I also tried this , but it returns me the count
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1) return -1; // error code if dates transposed
var iWeekday1 = dDate1.getDay(); // day of week
var iWeekday2 = dDate2.getDay();
iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
if (iWeekday1 <= iWeekday2) {
iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
alert(iDateDiff);
} else {
iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
}
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive
}
alert(calcBusinessDays(new Date("August 11, 2010 11:13:00"),new Date("August 16, 2010 11:13:00")));
Upvotes: 1
Views: 3790
Reputation: 318182
how can i get dates on saturday and sunday between two dates in javascript
Something like this would return all saturdays and sundays between two given days
function calcBusinessDays(dDate1, dDate2) {
if (dDate1 > dDate2) return false;
var date = dDate1;
var dates = [];
while (date < dDate2) {
if (date.getDay() === 0 || date.getDay() === 6) dates.push(new Date(date));
date.setDate( date.getDate() + 1 );
}
return dates;
}
var d1 = new Date(2015, 3, 3);
var d2 = new Date(2015, 5, 3);
function calcBusinessDays(dDate1, dDate2) {
if (dDate1 > dDate2) return false;
var date = dDate1;
var dates = [];
while (date < dDate2) {
if (date.getDay() === 0 || date.getDay() === 6) dates.push(new Date(date));
date.setDate( date.getDate() + 1 );
}
return dates;
}
document.body.innerHTML = '<pre>' + JSON.stringify(calcBusinessDays(d1,d2), null, 4) + '</pre>';
Upvotes: 4