WEB
JavaScript에서 주말을 제외하고 지정된 날짜에서 +3일을 계산하는 방법
iiaii
2023. 5. 12. 09:56
반응형
JavaScript에서 주말을 제외하고 지정된 날짜에서 +3일을 계산하는 방법
function addBusinessDays(startDate, numDays) {
var currentDate = new Date(startDate.getTime());
var businessDaysAdded = 0;
while (businessDaysAdded < numDays) {
currentDate.setDate(currentDate.getDate() + 1);
// 주말인지 확인 (토요일: 6, 일요일: 0)
if (currentDate.getDay() !== 0 && currentDate.getDay() !== 6) {
businessDaysAdded++;
}
}
return currentDate;
}
// 사용 예시
var startDate = new Date('2023-05-10'); // 시작 날짜
var numDays = 3; // 추가하려는 일 수
var resultDate = addBusinessDays(startDate, numDays);
console.log(resultDate); // 결과 출력
이 코드는 **addBusinessDays**라는 함수를 정의하고, 시작 날짜와 추가하려는 일 수를 인자로 받습니다. 함수는 주말을 제외한 영업일을 계산하여 결과 날짜를 반환합니다.
함수는 현재 날짜를 나타내는 currentDate 변수를 사용합니다. currentDate 변수는 **startDate**로 초기화되며, 계산 중에 변경됩니다.
while 루프는 businessDaysAdded 변수가 **numDays**와 같아질 때까지 반복됩니다. 각 반복마다 **currentDate**의 날짜를 하루씩 증가시킵니다.
그런 다음 **currentDate**의 요일을 확인하여 주말인 경우 **businessDaysAdded**를 증가시키지 않고, 평일인 경우에만 **businessDaysAdded**를 증가시킵니다.
while 루프가 완료되면 **currentDate**는 원하는 결과 날짜가 됩니다. 이를 반환하여 출력하면 됩니다.
위의 예시에서는 시작 날짜로 '2023-05-10'을 사용하고, 3일을 추가하였습니다. 따라서 결과로 '2023-05-15' (토요일과 일요일은 제외)가 출력됩니다.
반응형