- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 three properties, namely −
weeks, months, years, days
And the properties should have proper values of these four properties that can be made from the number of days. We should not consider leap years here and consider all years to have 365 days.
For example −
If the input is 738, then the output should be −
const output = { years: 2, months: 0, weeks: 1, days: 1 }
Example
Let’s write the code for this function −
const days = 738; const calculateTimimg = 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(calculateTimimg(days));
Output
The output in the console: −
{ years: 2, months: 0, weeks: 1, days: 1 }
Advertisements