Day of Year

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to calculate the day of the year in JavaScript using the Date object. By utilizing the Date constructor and Date.prototype.getFullYear(), we will create a function that returns the current day of the year as a number ranging from 1 to 366. This lab is designed to help you enhance your JavaScript skills and improve your understanding of date manipulation in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28252{{"`Day of Year`"}} javascript/data_types -.-> lab-28252{{"`Day of Year`"}} javascript/arith_ops -.-> lab-28252{{"`Day of Year`"}} javascript/comp_ops -.-> lab-28252{{"`Day of Year`"}} end

How to Get the Day of the Year in JavaScript using Date Object

To get the day of the year (number between 1-366) from a Date object in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Date constructor and Date.prototype.getFullYear() to get the first day of the year as a Date object.
  3. Subtract the first day of the year from the date object and divide by the milliseconds in each day to get the result.
  4. Use Math.floor() to round the resulting day count to an integer.

Here's the code:

const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

To test the function, call dayOfYear() with a Date object as the argument:

dayOfYear(new Date()); // 272

Summary

Congratulations! You have completed the Day of Year lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like