Primero tengo una fecha (formato de: dd, mm, aaaa) ex: 21, 3, 2012 y la convertí a un número de serie que en este caso sería 40988. Ahora para mi problema quiero encontrar un algoritmo que devuelva el número de días dado inicialmente por lo que en el ejemplo sería 21 . Este es el código que usé para convertir la fecha al número de serie:
//intYears, intMonths, intDays are parameter variables var serial = 0 //Going from 1900 to intYears - 1 (excluding the last year) var arrNormalYears = new Array() for (let i = 1900; i < intYears; i++) { arrNormalYears.push(i) } //Count the number of normal years excluding the //parameter year (intYear) //the function numberOfDaysYear checks for us if the //year is a leap year or a normal year var normalYears = 0 for (let j = 0; j < arrNormalYears.length; j++) { if (numberOfDaysYear(arrNormalYears[j]) == 365) { normalYears += 1 } } //multiply the count and add it to serial serial += normalYears * 365 //Same process for leap years var arrLeapYears = new Array() for (let m = 1900; m < intYears; m++) { arrLeapYears.push(m) } //Count the number of leap years var leapYears = 0 for (let a = 0; a < arrLeapYears.length; a++) { if (numberOfDaysYear(arrLeapYears[a]) == 366) { leapYears += 1 } } serial += leapYears * 366 //Now including the parameter variable intYear //Using the same process as above except this time //its for the months var arrMonths = new Array() for (let k = 1; k < intMonths; k++) { arrMonths.push(k) } //Here the function numberOfDaysMonth gives us the //number of days for the specific month, it also //checks if it's a leap year //also excluding the last month for (let x = 0; x < arrMonths.length; x++) { if (numberOfDaysMonth(arrMonths[x]) == 31) { serial += 31 } else if (numberOfDaysMonth(arrMonths[x]) == 30) { serial += 30 } else if (numberOfDaysMonth(arrMonths[x]) == 28) { serial += 28 } else if (numberOfDaysMonth(arrMonths[x]) == 29) { serial += 29 } } //Simply adding the days that are left serial += intDays return serial }Ahora, al comprender mi algoritmo utilizado para convertir la fecha en un número de serie, tengo problemas para revertir el algoritmo y devolver los días como se explica arriba del código.
Debe usar setDate y reemplazar el número de días en lugar de agregarlo como han dicho otros. El constructor JS Date permite números que son más grandes de lo que normalmente pensaría que están permitidos y proporciona la fecha correcta.
let serial = 40988; let dayOfMonth = new Date(1900, 0, serial).getDate(); console.log(dayOfMonth);ACTUALIZAR
Si configura la serie como cero, obtendrá el 31 de diciembre de 1899: ¡ha logrado recrear OADate! Ni siquiera me di cuenta de que originalmente
PRECAUCIÓN
JavaScript se ocupa de las fechas en su zona horaria local. Siempre que se adhiera a una sola zona horaria (local/UTC/lo que sea), debería estar bien.