JavaScript calcula el día del año (1 - 366)

Resuelto asked hace 13 años • 28 respuestas

¿Cómo uso JavaScript para calcular el día del año, del 1 al 366?

Por ejemplo:

  • January 3debiera ser 3.
  • February 1debiera ser 32.
 avatar Dec 24 '11 02:12
Aceptado

Siguiendo la edición de OP:

var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
Expandir fragmento

Editar: El código anterior fallará cuando nowsea una fecha entre el 26 de marzo y el 29 de octubre y nowla hora sea anterior a la 1 a. m. (por ejemplo, 00:59:59). Esto se debe a que el código no tiene en cuenta el horario de verano. Deberías compensar esto:

var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
Expandir fragmento

Alex Turpin avatar Dec 23 '2011 19:12 Alex Turpin

Me parece muy interesante que nadie haya considerado usar UTC ya que no está sujeto al horario de verano. Por ello propongo lo siguiente:

function daysIntoYear(date){
    return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}

Puedes probarlo con lo siguiente:

[new Date(2016,0,1), new Date(2016,1,1), new Date(2016,2,1), new Date(2016,5,1), new Date(2016,11,31)]
    .forEach(d => 
        console.log(`${d.toLocaleDateString()} is ${daysIntoYear(d)} days into the year`));

Qué resultados para el año bisiesto 2016 (verificado usando http://www.epochconverter.com/days/2016 ):

1/1/2016 is 1 days into the year
2/1/2016 is 32 days into the year
3/1/2016 is 61 days into the year
6/1/2016 is 153 days into the year
12/31/2016 is 366 days into the year
user2501097 avatar Dec 05 '2016 13:12 user2501097