w3resource

JavaScript: Get the quarter of the year

JavaScript Datetime: Exercise-15 with Solution

Write a JavaScript function to get the quarter (1 to 4) of the year.

Test Data:
console.log(quarter_of_the_year(new Date(2015, 1, 21)));
2
console.log(quarter_of_the_year(new Date(2015, 10, 18)));
4

Sample Solution:

JavaScript Code:

// Define a JavaScript function called quarter_of_the_year with parameter date
function quarter_of_the_year(date) 
{
  // Get the month component of the provided date and add 1 (as months are zero-based) and store it in the variable month
  var month = date.getMonth() + 1;
  // Calculate the quarter of the year by dividing the month by 3 and rounding up to the nearest integer
  return (Math.ceil(month / 3));
}

// Output the quarter of the year for the current date
console.log(quarter_of_the_year(new Date()));
// Output the quarter of the year for February 21, 2015
console.log(quarter_of_the_year(new Date(2015, 1, 21))); 
// Output the quarter of the year for November 18, 2015
console.log(quarter_of_the_year(new Date(2015, 10, 18)));

Output:

2
1
4

Explanation:

In the exercise above,

  • The code defines a JavaScript function named "quarter_of_the_year()" with one parameter 'date', representing a Date object.
  • Inside the function:
    • It extracts the month component from the provided date using the "getMonth()" method, which returns a zero-based index representing the month (0 for January, 1 for February, etc.).
    • It adds 1 to the month index to convert it to a 1-based index (1 for January, 2 for February, etc.) and stores it in the variable 'month'.
    • It calculates the quarter of the year by dividing the month by 3 and rounding up to the nearest integer using "Math.ceil()".
  • The function returns the calculated quarter of the year.
  • The code then demonstrates the usage of the "quarter_of_the_year()" function by calling it with three different Date objects:
    • The current date (obtained using new Date())
    • February 21, 2015 (created using new Date(2015, 1, 21), where the month is 1 for February)
    • November 18, 2015 (created using new Date(2015, 10, 18), where the month is 10 for November)
  • Each console.log() call outputs the quarter of the year for the respective date to the console.

Flowchart:

Flowchart: JavaScript- Get the quarter  of the year

Live Demo:

See the Pen JavaScript - Get the quarter of the year-date-ex- 15 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the amount of days of a year.
Next: Write a JavaScript function to count the number of days passed since beginning of the year.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.