Poiché la definizione di "età in mesi" è... flessibile, il modo più semplice è quello di utilizzare un po ' di aritmetica, come si dovrebbe calcolare in testa, e non comportano la Date
classe.
Per [a] interpretazione umana di "età in mesi", la regola è
Calcolare la differenza tra due date in mesi,
come se il giorno del mese è stato il 1 ° del mese per entrambe le date
Sottrarre 1 per escludere l'ultimo mese
Quindi, se il giorno del mese, dell' ultimo giorno del periodo è
o dopo il giorno del mese, il primo giorno del periodo, il [potenzialmente parziale] l'ultimo mese è completo: aggiungere 1 per ripristinare il conteggio
L'unico neo è, da mesi, contengono un diverso numero di giorni, occupandosi di casi in cui i 2 mesi differiscono nel numero di giorni.
Se, tuttavia, il fine mese è inferiore a inizio mese, è possibile ottenere in una situazione in cui la condizione al contorno non possono mai essere soddisfatte (ad esempio, la data di inizio è il 28 febbraio e la data di scadenza è il 31 Marzo. Per risolvere questo problema, è necessario guardare alla "fine del mese" come una finestra che vanno dall'ultimo giorno del mese di inizio attraverso l'ultimo giorno del mese di fine inclusive.
Che porta a questo codice. Sto utilizzando una struttura come la seguente per rappresentare una data:
{
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
}
Garantire che i dati in tale struttura rappresenta una data valida è lasciato come esercizio per il lettore.
Il codice non è così complicato:
/**
*
* @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())
sarà quasi certamente tornare una Data non valida.