Get the day of the year in JavaScript

in Code Write a comment

In this tutorial, you’ll learn how to get the day of the year from a Date object in JavaScript. Here’s an example below, dayOfTheYear() function will return the current day of the year.

dayOfTheYear(new Date()); // 236


We’re using Date.prototype.getFullYear() and Date() to the get the first day of the year and subtract one from another and divide by the milliseconds in a day. Finally, we’re using Math.floor() to round the result and print it as an integer.

function dayOfTheYear(date) {
  return Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

Hi, I'm Renat 👋


If you find this post useful, please let me know in the comments below. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other JavaScript tutorials, e.g. how to separate numbers with commas in JavaScript or generate an array of years in JavaScript.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment