Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

50
Views
How to convert seconds to biggest significative time unit

What would be the cleanest way to convert an amount of seconds to the biggest unit that is not 0 and then display only the significative unit.

Input -> Expected output
1 -> 1s
61 -> 1m
120 -> 2m
3620 -> 1h
86400 -> 1day
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

const units = [
  [1, "s"],
  [60, "m"],
  [60 * 60, "h"],
  [60 * 60 * 24, "day"]
];

function displayTime(seconds) {
  let bestUnit = units[0];
  for(const unit of units) {
    if(seconds >= unit[0]) {
        bestUnit = unit;
    }
  }
  const [divisor, label] = bestUnit;
  return Math.floor(seconds /divisor) + label;
}

console.log(displayTime(1)); // 1s
console.log(displayTime(61)); // 1m
console.log(displayTime(120)); // 2m
console.log(displayTime(3620)); // 1h
console.log(displayTime(86400)); // 1day

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs