
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Finding nth day of the year in leap and non-leap years in JavaScript
Problem
We are required to write a JavaScript function that takes in a number as the first argument and boolean as the second argument.
The boolean specifies a leap year (if it’s true). Based on this information our function should return the date that would fall on the nth day of the year.
Example
Following is the code −
const day = 60; const isLeap = true; const findDate = (day = 1, isLeap = false) => { if(day > 366){ return undefined; }; const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; if(isLeap){ days[1]++; }; let i = -1, count = 0; while(count < day){ i++; count += days[i]; }; const upto = days.slice(0, i).reduce((acc, val) => acc + val); const month = months[i]; const d = count - upto; return `${month}, ${d}`; }; console.log(findDate(day, isLeap));
Output
Following is the console output −
Feb, 29
- Related Articles
- Finding next n leap years in JavaScript
- JavaScript program to check if a given year is leap year
- How to check whether a year or a vector of years is leap year or not in R?
- C++ Program to Check Leap Year
- Java Program to Check Leap Year
- Check if a given year is leap year in PL/SQL
- How to Check Leap Year using Python?
- Checking for a Leap Year using GregorianCalendar in Java
- Program to check if a given year is leap year in C
- How can we calculate the number of seconds in a leap year?
- What is the probability of getting $53$ Mondays in a leap year?
- What do you mean by a leap year?
- Finding day of week from date (day, month, year) in JavaScript
- How to find leap year or not in android using year API class?
- How to detect if a given year is a Leap year in Oracle?

Advertisements