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

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.

I developed a Vue.js starter kit that you can order today

Order Vue.js starter kit

Write a Comment