Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding the nth day from today - JavaScript (JS Date)
We are required to write a JavaScript function that takes in a number n as the only input.
The function should first find the current day (using Date Object in JavaScript) and then the function should return the day n days from today.
For example −
If today is Monday and n = 2,
Then the output should be −
Wednesday
Understanding the Problem
JavaScript's Date.getDay() returns 0 for Sunday, 1 for Monday, and so on. We need to handle the modulo operation correctly to cycle through weekdays.
Method 1: Using Array Index Mapping
const num = 15;
const findNthDay = num => {
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const today = new Date().getDay();
const targetDay = (today + num) % 7;
return weekdays[targetDay];
};
console.log(`Today: ${new Date().toDateString()}`);
console.log(`${num} days from now: ${findNthDay(num)}`);
Today: Mon Dec 09 2024 15 days from now: Tuesday
Method 2: Using Date Addition
const findNthDayByDate = num => {
const today = new Date();
const futureDate = new Date(today);
futureDate.setDate(today.getDate() + num);
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
return weekdays[futureDate.getDay()];
};
console.log(`5 days from now: ${findNthDayByDate(5)}`);
console.log(`30 days from now: ${findNthDayByDate(30)}`);
5 days from now: Saturday 30 days from now: Wednesday
Complete Example with Current Day Display
const getDayInfo = num => {
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const today = new Date();
const currentDay = weekdays[today.getDay()];
const targetDay = weekdays[(today.getDay() + num) % 7];
return {
today: currentDay,
nDaysLater: targetDay,
calculation: `(${today.getDay()} + ${num}) % 7 = ${(today.getDay() + num) % 7}`
};
};
const result = getDayInfo(10);
console.log(`Today is: ${result.today}`);
console.log(`10 days from now: ${result.nDaysLater}`);
console.log(`Calculation: ${result.calculation}`);
Today is: Monday 10 days from now: Thursday Calculation: (1 + 10) % 7 = 4
Key Points
-
getDay()returns 0-6 where Sunday = 0 - Use modulo operator (%) to cycle through days of the week
- Method 2 handles month/year transitions automatically
- Both approaches work for negative numbers (past dates)
Conclusion
Both methods effectively calculate the nth day from today. The array-based approach is simpler for day-name calculations, while the Date addition method handles complex date arithmetic automatically.
Advertisements
