我正在使用Nodejs编写一个rest api,允许用户申请离开.
输入是
>天数(noOfLeaves).
>从日期开始(我用这一天来决定周末和跳月).
>月内没有天数(如果是跳至下个月).
我使用fromDate来获取月份和开始日期.
我正在实现一个检查两个条件的逻辑.
a)如果是周末(坐/太阳),请跳到平日.
b)如果月末结束,请跳至下个月.
我的下面的逻辑跳过了周末,但重复了工作日.
可能是什么问题,任何更好的方法来实现这一目标.
var splitDat = '2016-05-27'.split("-", 3);
var nxtMonthDay = 1;
var j = 0;
var noOfDaysForThisMonth = new Date(parseInt(splitDat[0]), parseInt(splitDat[1]), 0).getDate();
var noOfLeaves = 5;
for (var i = 0; i < noOfLeaves; i++) {
var inputYear = parseInt(splitDat[0]);
var inputMonth = parseInt(splitDat[1]);
var inputDay = parseInt(splitDat[2]);
if (parseInt(inputDay) + i > noOfDaysForThisMonth) {
inputMonth = inputMonth + 1
inputDay = nxtMonthDay + j;
j++;
} else {
inputDay = inputDay + i;
}
var dayVal = new Date(inputYear, (parseInt(inputMonth) - 1), inputDay).getDay();
// console.log('Day value : ' + dayVal);
if (dayVal == 6) {
if ((inputDay + 2) > noOfDaysForThisMonth) {
inputDay = nxtMonthDay;
} else {
inputDay = inputDay + 2;
}
// console.log('Saturday');
} else if (dayVal == 0) {
// console.log('Sunday');
if ((inputDay + 3) > noOfDaysForThisMonth) {
if ((inputDay + 2) > noOfDaysForThisMonth) {
inputDay = nxtMonthDay;
} else {
inputDay = inputDay + 2;
}
} else {
inputDay = inputDay + 3;
}
}
console.log(inputYear+'-'+ inputMonth+'-'+ inputDay);
//this is a function call to create a leave entry in the database using year-month-day
ApplyLeave(inputYear, inputMonth, inputDay);
}
这给出了输出
> 2016-5-27
> 2016-5-30
> 2016-5-31
> 2016-5-30
> 2016-5-31
我期待输出为
> 2016-5-27
> 2016-5-30
> 2016-5-31
> 2016-6-01
> 2016-6-02
有人可以告诉我,如果我的逻辑是正确的,如果不是如何做到这一点?
最佳答案 我修好了,基本上你的问题是,当你试图查看日期是否大于几个月中的天数时,你使用“inputday”我,但问题是你没有考虑到你已经跳过了周末的日子,所以你总是将i递增1,而它应该按跳过的天数递增,所以我添加了另一个变量来修复它,以及更多的日志记录.
var splitDat = '2016-05-27'.split("-", 3);
var nxtMonthDay = 1;
var j = 0;
var noOfDaysForThisMonth = new Date(parseInt(splitDat[0]), parseInt(splitDat[1]), 0).getDate();
console.log("monthdays "+noOfDaysForThisMonth)
var noOfLeaves = 5;
var DaysPassed = 0;
for (var i = 0; i < noOfLeaves; i++) {
console.log(i);
var inputYear = parseInt(splitDat[0]);
var inputMonth = parseInt(splitDat[1]);
var inputDay = parseInt(splitDat[2]);
if (inputDay + DaysPassed > noOfDaysForThisMonth) {
inputMonth = inputMonth + 1
inputDay = nxtMonthDay + j;
j++;
} else {
inputDay = inputDay + i;
}
var dayVal = new Date(inputYear, (parseInt(inputMonth) - 1), inputDay).getDay();
console.log('Day value : ' + dayVal);
if (dayVal == 6) {
if ((inputDay + 2) > noOfDaysForThisMonth) {
inputDay = nxtMonthDay;
} else {
inputDay = inputDay + 2;
}
DaysPassed += 2;
console.log('Saturday');
} else if (dayVal == 0) {
console.log('Sunday');
DaysPassed += 3;
if ((inputDay + 3) > noOfDaysForThisMonth) {
if ((inputDay + 2) > noOfDaysForThisMonth) {
inputDay = nxtMonthDay;
} else {
inputDay = inputDay + 2;
}
} else {
inputDay = inputDay + 3;
}
DaysPassed++;
}
console.log(inputYear+'-'+ inputMonth+'-'+ inputDay);
} //this is a function call to create a leave entry in the database using year-month-day