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
Converting days into years months and weeks - JavaScript
We are required to write a JavaScript function that takes in a number (representing the number of days) and returns an object with four properties:
years, months, weeks, days
The properties should have proper values that can be made from the total number of days. We assume a standard year has 365 days and each month has 30 days for simplicity.
Problem Example
If the input is 738 days, the output should be:
{
years: 2,
months: 0,
weeks: 1,
days: 1
}
Solution Using Sequential Subtraction
The approach is to subtract the largest time unit first (years), then months, weeks, and finally remaining days:
const days = 738;
const calculateTiming = d => {
let months = 0, years = 0, days = 0, weeks = 0;
while(d){
if(d >= 365){
years++;
d -= 365;
}else if(d >= 30){
months++;
d -= 30;
}else if(d >= 7){
weeks++;
d -= 7;
}else{
days++;
d--;
}
};
return {
years, months, weeks, days
};
};
console.log(calculateTiming(days));
{ years: 2, months: 0, weeks: 1, days: 1 }
Alternative Solution Using Division
A more efficient approach using mathematical division and remainder operations:
const calculateTimingOptimized = totalDays => {
let remaining = totalDays;
const years = Math.floor(remaining / 365);
remaining = remaining % 365;
const months = Math.floor(remaining / 30);
remaining = remaining % 30;
const weeks = Math.floor(remaining / 7);
const days = remaining % 7;
return { years, months, weeks, days };
};
// Test with different values
console.log(calculateTimingOptimized(738)); // 738 days
console.log(calculateTimingOptimized(400)); // 400 days
console.log(calculateTimingOptimized(50)); // 50 days
{ years: 2, months: 0, weeks: 1, days: 1 }
{ years: 1, months: 1, weeks: 0, days: 5 }
{ years: 0, months: 1, weeks: 2, days: 6 }
How It Works
The calculation follows this hierarchy:
- 1 year = 365 days
- 1 month = 30 days
- 1 week = 7 days
- Remaining = days
For 738 days: 738 ÷ 365 = 2 years (730 days), leaving 8 days. Then 8 ÷ 7 = 1 week (7 days), leaving 1 day.
Conclusion
Both approaches work effectively, but the mathematical division method is more efficient than the loop-based subtraction. Choose the division approach for better performance with large numbers.
