Ever wanted to know what numerical "day of the year" a date falls on (e.g., January 31st is day 31, but February 1st is day 32)?
We can do this easily by subtracting January 1st from our target date and converting milliseconds into days!
JavaScript
function dayOfTheYear(date) {
const year = date.getFullYear();
// Get January 1st of that exact year
const startOfYear = new Date(year, 0, 1);
// Find the difference in milliseconds
const diffTime = date.getTime() - startOfYear.getTime();
// Convert milliseconds to days (1000ms * 60s * 60m * 24hrs)
// Plus 1 because January 1st itself is Day 1, not Day 0!
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24)) + 1;
return diffDays;
}
console.log(dayOfTheYear(new Date("2026-01-01"))); // Output: 1
console.log(dayOfTheYear(new Date("2026-02-01"))); // Output: 32
Top comments (0)