Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  55] [ 1]  / answers: 1 / hits: 159671  / 13 Years ago, fri, december 23, 2011, 12:00:00

How do I use JavaScript to calculate the day of the year, from 1 - 366?


For example:



  • January 3 should be 3.

  • February 1 should be 32.


More From » javascript

 Answers
68

Following OP's edit:





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);





Edit: The code above will fail when now is a date in between march 26th and October 29th andnow's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:





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);




[#88399] Thursday, December 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yosefleod

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago
;