yyyy una tipos regulares que pasar parametros obtener numeros hora funciones funcion formato fecha expresiones especiales desde caracteres actual javascript date

tipos - pasar parametros a una funcion javascript desde html



¿Cuál es la mejor manera de determinar el número de días en un mes con JavaScript? (11)

He estado usando esta función, pero me gustaría saber cuál es la forma más eficiente y precisa de obtenerla.

function daysInMonth(iMonth, iYear) { return 32 - new Date(iYear, iMonth, 32).getDate(); }


Algunas respuestas (también en otras preguntas) tenían problemas año bisiesto o usaban el objeto Fecha. Aunque el Date object de JavaScript abarca aproximadamente 285616 años (100,000,000 de días) en cualquier lado del 1 de enero de 1970, estaba harto de todo tipo de inconsistencies fechas inesperadas en diferentes navegadores (más notablemente en el año 0 al 99). También tenía curiosidad por cómo calcularlo.

Así que escribí un algoritmo simple y, sobre todo, pequeño para calcular el correcto ( Proleptic Gregorian / Astronomical / ISO 8601: 2004 (cláusula 4.3.2.1), por lo que el año 0 existe y es un año bisiesto y se admiten años negativos ) número de días para un mes y año dados.
Utiliza el algoritmo short-circuit bitmask-modulo leapYear (ligeramente modificado para js) y el algoritmo común de mod-8 meses.

Tenga en cuenta que en la notación AD/BC , el año 0 AD / BC no existe: en cambio, el año 1 BC es el año bisiesto.
¡Si necesita registrar la notación BC, simplemente restar un año del valor anual (de lo contrario positivo) primero! (O reste el año de 1 para cálculos anuales adicionales).

function daysInMonth(m, y){ return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1); }

<!-- example for the snippet --> <input type="text" value="enter year" onblur=" for( var r='''', i=0, y=+this.value ; 12>i++ ; r+= ''Month: '' + i + '' has '' + daysInMonth(i, y) + '' days<br>'' ); this.nextSibling.innerHTML=r; " /><div></div>

Nota: ¡los meses deben estar basados ​​en 1!

Tenga en cuenta que este es un algoritmo diferente, entonces la búsqueda de número mágico que utilicé en mi Javascript calcular el día del año (1 - 366) responde, porque aquí la rama adicional para el año bisiesto solo es necesaria para febrero.


Cómputo directo de una línea (sin objeto de fecha):

function daysInMonth(m, y) {//m is 1-based, feb = 2 return 31 - (--m ^ 1? m % 7 & 1: y & 3? 3: y % 25? 2: y & 15? 3: 2); } console.log(daysInMonth(2, 1999)); // February in a non-leap year console.log(daysInMonth(2, 2000)); // February in a leap year

Variación con meses basados ​​en 0:

function daysInMonth(m, y) {//m is 0-based, feb = 1 return 31 - (m ^ 1? m % 7 & 1: y & 3? 3: y % 25? 2: y & 15? 3: 2); }


Con moment.js puedes usar el método daysInMonth ():

moment().daysInMonth(); // number of days in the current month moment("2012-02", "YYYY-MM").daysInMonth() // 29 moment("2012-01", "YYYY-MM").daysInMonth() // 31


En una sola línea:

// month is 1-12 function getDaysInMonth(year, month){ return month == 2 ? 28 + (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : 1):0) : 31 - (month - 1) % 7 % 2; }


Para eliminar la confusión, probablemente haría la cadena del mes basada en que actualmente está basada en 1.

function daysInMonth(month,year) { monthNum = new Date(Date.parse(month +" 1,"+year)).getMonth()+1 return new Date(year, monthNum, 0).getDate(); } daysInMonth(''feb'', 2015) //28 daysInMonth(''feb'', 2008) //29


Quizás no sea la solución más elegante, pero fácil de entender y mantener; y, está probado en la batalla.

function daysInMonth(month, year) { var days; switch (month) { case 1: // Feb, our problem child var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); days = leapYear ? 29 : 28; break; case 3: case 5: case 8: case 10: days = 30; break; default: days = 31; } return days; },


Si desea la cantidad de días en el mes actual de un objeto Date, considere el siguiente método:

Date.prototype.getNumberOfDaysInMonth = function(monthOffset) { if (monthOffset !== undefined) { return new Date(this.getFullYear(), this.getMonth()+monthOffset, 0).getDate(); } else { return new Date(this.getFullYear(), this.getMonth(), 0).getDate(); } }

Entonces puedes ejecutarlo así:

var myDate = new Date(); myDate.getNumberOfDaysInMonth(); // Returns 28, 29, 30, 31, etc. as necessary myDate.getNumberOfDaysInMonth(); // BONUS: This also tells you the number of days in past/future months!


Si llama a esta función con frecuencia, puede ser útil guardar en caché el valor para obtener un mejor rendimiento.

Aquí está la versión de caché de la respuesta de FlySwat :

var daysInMonth = (function() { var cache = {}; return function(month, year) { var entry = year + ''-'' + month; if (cache[entry]) return cache[entry]; return cache[entry] = new Date(year, month, 0).getDate(); } })();


Teniendo en cuenta los años bisiestos:

function (year, month) { var isLeapYear = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); return [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }


function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc. return new Date(year, month, 0).getDate(); } console.log(daysInMonth(2, 1999)); // February in a non-leap year. console.log(daysInMonth(2, 2000)); // February in a leap year.

El día 0 es el último día del mes anterior. Como el constructor del mes está basado en 0, funciona bien. Un poco de hack, pero eso es básicamente lo que estás haciendo al restar 32.


function numberOfDays(iMonth, iYear) { var myDate = new Date(iYear, iMonth + 1, 1); //find the fist day of next month var newDate = new Date(myDate - 1); //find the last day return newDate.getDate(); //return # of days in this month }