-2

Is it possible to display the highest expanded whole number metric time with Javascript code,

For an application, I want to display a time but instead of having a set metric (hour, min or second) it's flexible and I want to display the highest expanded metric given a time value. The input would be in seconds, and if there's a value that exceeds 3 digits I want it to be converted to the next unit, so for example

Input: 1500s
Output: 25mins
Reason: In its most expanded form it would be 25mins


Input: 3245155s
Output: 90hrs
Reason: In its most expanded form it would be 90hrs because in mins it would be 5409 which exceeds my 3 digit limit for a whole number.

Input: 34s
Output: 34s
Reason: In its most expanded form it would remain 34s as it is still within my 3 digit range

I know it's possible to write an algorithm for this, but instead of reinventing the wheel I'd just like to know if this functionality is built-in Javascript

  • Not built in. Similar - https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site – James Mar 03 '22 at 16:18
  • Yes. Divide by various units, starting with either the largest or smallest, until you reach the condition for displaying a particular unit. Have a go, post some code. :-) – RobG Mar 04 '22 at 10:37
  • I actually did that after and it worked. Thanks! – Tahjyei Thompson Mar 04 '22 at 18:22

1 Answers1

0

This is the solution that works for me, dividing the various units (therefore converting) until I reach the final unit I'd use.

const timeFormatter = (seconds) => {
    if (!seconds) return "0s";

    if (seconds < 60) return `${seconds}s`;

    let minutes = Math.round(seconds / 60);

    if (minutes < 60) return `${minutes}min`;

    let hours = Math.round(minutes / 60);

    if (hours < 24) return `${hours}hr`;

    let days = Math.round(hours / 24);
    return `${days}d`;
};
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 04 '22 at 18:23