w3resource

JavaScript: Get the amount of days of a year

JavaScript Datetime: Exercise-14 with Solution

Write a JavaScript function to get the number of days in a year.

Test Data :
console.log(days_of_a_year(2015));
365
console.log(days_of_a_year(2016));
366

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to get the amount of days of a year</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function days_of_a_year(year) 
{
   
  return isLeapYear(year) ? 366 : 365;
}

function isLeapYear(year) {
     return year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0);
}

console.log(days_of_a_year(2015));
console.log(days_of_a_year(2016));

Sample Output:

365
366

Flowchart:

Flowchart: JavaScript- Get the amount of days of a year

Live Demo:

See the Pen JavaScript - Get the amount of days of a year-date-ex- 14 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function that will return the number of minutes in hours and minutes.
Next: Write a JavaScript function to get the quarter (1 to 4) 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.