我对浏览器结束脚本(如javascript)非常弱,因为我是一名php开发人员。我需要在星期六和星期天得到日期。我已经找到很多答案来计算数量但是没有找到办法在周六和周日得到日期。我试过这些:
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() );
它仅在下一个星期六的日期返回给我。请帮我解决这个问题
我也尝试过这个,但它会给我一个计数
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")));
答案 0 :(得分:3)
我怎样才能在星期六和星期日两个日期之间得到日期 的JavaScript
这样的事情会在两个特定的日子之间返回所有星期六和星期日
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>';