Converting seconds in years days hours and minutes in JavaScript


Problem

We are required to write a JavaScript function that takes in a number, num, that represents the number of seconds as the first and the only argument.

Our function should then construct and return a string that contains information of years, days, hours and minutes contained in those seconds, obviously if contained at all.

For the purpose of this question, we consider that all the years have 365 days

For example, if the input to the function is −

const num = 5454776657;

Then the output should be −

const output = '172 years, 353 days, 23 hours, 44 minutes and 17 seconds';

Example

Following is the code −

const findTime = (num) => {
   if(num < 1){
      return '0'
   };
   const qualifier = num => (num > 1 ? 's' : '')
   const numToStr = (num, unit) => num > 0 ? ` ${num}
   ${unit}${qualifier(num)}` : ''
   const oneMinute = 60;
   const oneHour = oneMinute * 60;
   const oneDay = oneHour * 24;
   const oneYear = oneDay * 365;
   const times = {
      year: ~~(num / oneYear),
      day: ~~((num % oneYear) / oneDay),
      hour: ~~((num % oneDay) / oneHour),
      minute: ~~((num % oneHour) / oneMinute),
      second: num % oneMinute,
   };
   let str = '';
   for (let [key, value] of Object.entries(times)) {
      str += numToStr(times[key], key)
   }
   const arr = str.trim().split(' ')
   const res = []
   arr.forEach((x, i) => {
      if (i % 2 === 0 && i !== 0) res.push(i === arr.length - 2 ? 'and' : ',')
      res.push(x)
   })
   return res.join(' ').replace(/\s,/g, ',')
}
console.log(findTime(5454776657));

Output

Following is the console output −

172 years, 353 days, 23 hours, 44 minutes and 17 seconds

Updated on: 21-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements