Scriptdrill

Level 3: Strings and dates Exercise 26 of 45 Pro

Format a duration

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Format a whole number of seconds like `"1d 2h 3m 4s"`, using days, hours, minutes and seconds, largest first. Leave out units that are zero. Zero seconds is `"0s"`.

What this exercise teaches

Taking the largest unit first and carrying the remainder down gives each unit its share. Zero parts are skipped, and joining an empty list gives "", which the fallback turns into "0s".

A hint if you get stuck

Go through `[["d", 86400], ["h", 3600], ["m", 60], ["s", 1]]`. For each unit take `Math.floor(rest / size)`, keep it when it is not zero, and subtract it from the rest.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Strings and dates