Quarter of Year

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the concept of date and time manipulation in JavaScript. We will be focusing on a specific function, quarterOfYear, which takes in a date and returns the quarter and year to which the date belongs. By the end of the lab, you will have a solid understanding of how to extract and manipulate date and time information 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-28564{{"`Quarter of Year`"}} javascript/data_types -.-> lab-28564{{"`Quarter of Year`"}} javascript/arith_ops -.-> lab-28564{{"`Quarter of Year`"}} javascript/comp_ops -.-> lab-28564{{"`Quarter of Year`"}} end

Function to Determine Quarter of Year

To determine the quarter of the year, use the quarterOfYear() function. This function takes an optional date argument and returns an array with the quarter and year to which the supplied date belongs.

To use this function, open the Terminal/SSH and type node. Then, copy and paste the following code:

const quarterOfYear = (date = new Date()) => [
  Math.ceil((date.getMonth() + 1) / 3),
  date.getFullYear()
];

The quarterOfYear() function uses the following steps to calculate the quarter and year:

  • Uses Date.prototype.getMonth() to get the current month in the range (0, 11), adds 1 to map it to the range (1, 12).
  • Uses Math.ceil() and divides the month by 3 to get the current quarter.
  • Uses Date.prototype.getFullYear() to get the year from the given date.
  • Omits the argument, date, to use the current date by default.

Here are some examples of how to use the quarterOfYear() function:

quarterOfYear(new Date("07/10/2018")); // [ 3, 2018 ]
quarterOfYear(); // [ 4, 2020 ]

Summary

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

Other JavaScript Tutorials you may like