기 때문에 정의"시대에 개월은"...가동 가능한 가장 쉬운 방법을 사용하는 것이 작은 연산으로 계산은 그것의 머리에서,그리고련 Date
클래스입니다.
를[a]인간의 해석"시대에 개월 동안",규칙이
계산 둘 사이의 차이점은 날짜에 개월
럼 하루-of-the-달의 1 일에 달한 날짜
빼기 1 을 제외할 최종 한 달
그런 다음 경우,day-of-the-달의 마지막 날의 기간에
또는 후에 하루의-달의 첫째 날의 기간,[잠재적으로 부]최종 개월이 완료:추가 1 을 복원 계산
하나에서 비행 연고,이후 개월 동안 다른 숫자를 포함한 일을 다루는 경우가 2 개월 만에 다수의 일입니다.
는 경우,그러나 결국 달보다 짧은 시작 월,당신이 얻을 수 있는 상황으로 경계 조건이 될 수 없을 만났(예를 들어 시작 날짜 월 28 일과 종료일은 월 31 일. 그 문제를 해결하기 위해,당신은에서 볼 필요가"end"달의 것으로는 창에 이르기까지의 마지막 날에 시작하는 달의 마지막 날을 통해 최종달을 포함한다.
에 이르게 하는 코드입니다. 나는 구조를 사용하여 다음과 같이를 나타내는 날짜:
{
year: 2021 , // 4-digit year
month: 11 , // month of year (1-12 mapping to January-December)
day: 23 // day of month (1-[28-31] depending on year/month
}
을 보장하는 데이터에서는 구조체를 나타내는 유효한 날짜은 왼쪽으로는 운동에 대한 독자입니다.
코드가 복잡하지 않습니다:
/**
*
* @param {object} bgn - start date of period
* @param {number} bgn.year - 4-digit year
* @param {number} bgn.month - month of year [1-12]
* @param {number} bgn.day - day of month [1-31]
*
* @param {object} end - end date of period
* @param {number} end.year - 4-digit year
* @param {number} end.month - month of year [1-12]
* @param {number} end.day - day of month [1-31]
*
*/
function diffInMonths( bgn , end ) {
const between = ( x , min , max ) => x >= min && x <= max;
// We'll need to add back the final month based on the following:
// - end.day >= bgn.day -- we've passed the month boundary, or
// - end.day is within the end-of-month window
// (when the end month is shorter than the start month)
const needAdjustment = end.day >= bgn.day
|| between( end.day, daysInMonth(bgn), daysInMonth(end) );
const finalMonthAdjustment = needsAdjustment ? 1 : 0;
const deltaM = 12 * ( end.year - bgn.year )
+ ( end.month - bgn.month )
- 1 // remove the final month from the equation
+ finalMonthAdjustment // add in the precomputed final month adjustment
;
return deltaM;
}
/**
*
* @param {object} dt - date
* @param {number} dt.year - 4-digit year
* @param {number} dt.month - month of year [1-12]
* @param {number} dt.day - day of month [1-31]
*
*/
function daysInMonth(dt) {
const leapYear = ( dt.year % 4 === 0 && dt.year % 100 !== 0 ) || dt.year % 400 === 0;
const monthDays = leapYear ? daysPerMonthLeap : daysPerMonth;
const days = monthDays[dt.month];
return days;
}
// jan feb mar apr may jun jul aug sep oct nov dec
// ---------- --- --- --- --- --- --- --- --- --- --- --- ---
const daysPerMonth = [ undefined, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ];
const daysPerMonthLeap = [ undefined, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ];
new Date(userDate.split('/').reverse())
이 거의 확실하게 반환 잘못된 날짜입니다.