Format a duration like 2h 15m in JavaScript
Intermediate · 3 min read
"Estimated time: 2h 15m." "Uptime: 3d 4h." "Video length: 45m." Apps show durations in short labels like these because "135 minutes" makes the reader do the maths. A good label shows the biggest units and drops the tiny ones nobody cares about.
In this tutorial you will turn a number of minutes into labels like 2h 15m and 1d 1h. You'll keep only the two largest units that aren't zero, print 0m for nothing, and handle negative durations. You need to know arrays, push and join. Dividing with a remainder is explained below.
Splitting minutes into days, hours and minutes
There are 60 minutes in an hour and 1440 (24 × 60) in a day. To split 1501 minutes:
- Whole days:
Math.floor(1501 / 1440)is 1. That uses 1440 minutes, leaving 61. - Whole hours in what's left:
Math.floor(61 / 60)is 1, leaving 1. - The last 1 is minutes.
So 1501 minutes is 1 day, 1 hour and 1 minute. Math.floor rounds down to a whole number, which is what "how many whole days fit?" means.
console.log(Math.floor(1501 / 1440)); // 1
console.log(1501 - 1 * 1440); // 61
console.log(Math.floor(61 / 60)); // 1
console.log(61 - 1 * 60); // 1
Always start with the largest unit and work down.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
133 A duration a person can read
fairTurn a number of minutes into 2h 15m, 1d 1h, 45m. Show only the two largest units that are not zero, keep 0m for nothing, and handle a negative duration.
Stuck? Three hints, smallest first
- 1. Divide and take the remainder, largest unit first.
- 2. Collect the non-zero parts into an array, then take the first two.
- 3. Deal with the sign once, at the start, and work with the absolute value.
Step 1: compute the three numbers
const MINUTES_IN_DAY = 24 * 60;
function split(totalMinutes) {
let left = totalMinutes;
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
return [days, hours, minutes];
}
console.log(split(135)); // [ 0, 2, 15 ]
console.log(split(1501)); // [ 1, 1, 1 ]
console.log(split(1441)); // [ 1, 0, 1 ]
left holds what's still to be shared out. After taking the days, it's only what didn't fit into a whole day.
Step 2: keep only the parts that aren't zero
A label like 0d 2h 15m is noisy. Collect a part only when it isn't zero:
const MINUTES_IN_DAY = 24 * 60;
function parts(totalMinutes) {
let left = totalMinutes;
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
const out = [];
if (days) out.push(days + 'd');
if (hours) out.push(hours + 'h');
if (minutes) out.push(minutes + 'm');
return out;
}
console.log(parts(135)); // [ '2h', '15m' ]
console.log(parts(1441)); // [ '1d', '1m' ]
console.log(parts(0)); // []
console.log(parts(0).join(' ') || '0m'); // 0m
if (days) is true for any number except 0, so zero parts are skipped. That's why 1441 gives 1d 1m, not 1d 0h 1m.
When there's nothing at all, the array is empty and join gives an empty string. || '0m' means "or, if that's empty, use 0m". An empty string is falsy, so the fallback kicks in.
Step 3: keep the two largest
slice(0, 2) takes the first two items of the array. Because we pushed the largest units first, these are the two that matter most:
const MINUTES_IN_DAY = 24 * 60;
function parts(totalMinutes) {
let left = totalMinutes;
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
const out = [];
if (days) out.push(days + 'd');
if (hours) out.push(hours + 'h');
if (minutes) out.push(minutes + 'm');
return out;
}
const full = (m) => parts(m).join(' ') || '0m';
const brief = (m) => parts(m).slice(0, 2).join(' ') || '0m';
console.log(full(1501), '|', brief(1501)); // 1d 1h 1m | 1d 1h
console.log(brief(60)); // 1h
console.log(brief(1440)); // 1d
The dropped unit is always the smallest one, so the label is never off by much. Dropping the largest unit instead would be a disaster: 1h 1m for a duration of more than a day.
Step 4: negative durations
Try a negative number with what we have:
const MINUTES_IN_DAY = 24 * 60;
function parts(totalMinutes) {
let left = totalMinutes;
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
const out = [];
if (days) out.push(days + 'd');
if (hours) out.push(hours + 'h');
if (minutes) out.push(minutes + 'm');
return out;
}
console.log(parts(-90)); // [ '-1d', '22h', '30m' ]
Math.floor rounds negative numbers down, away from zero, so -90 minutes becomes "minus one day plus 22 and a half hours". That's correct arithmetic and useless as a label.
The fix: deal with the sign once, at the start. Work with the absolute value (Math.abs), and put a minus in front at the end. Math.trunc also cuts off any fraction of a minute:
const MINUTES_IN_DAY = 24 * 60;
function parts(totalMinutes) {
let left = Math.abs(Math.trunc(totalMinutes));
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
const out = [];
if (days) out.push(days + 'd');
if (hours) out.push(hours + 'h');
if (minutes) out.push(minutes + 'm');
return out;
}
const brief = (m) => (m < 0 ? '-' : '') + (parts(m).slice(0, 2).join(' ') || '0m');
console.log(brief(-90)); // -1h 30m
console.log(brief(90.9)); // 1h 30m
console.log(brief(-0.5)); // -0m
The last line is a small loose end: -0.5 minutes truncates to nothing, but the sign comes from the original number. If your durations can be fractional, round them before they reach the formatter.
The full solution
The answer panel has parts, full and brief, and prints both labels for eight durations from 0 to 1501 minutes. Press Run to see the output.
const MINUTES_IN_DAY = 24 * 60;
function parts(totalMinutes) {
let left = Math.abs(Math.trunc(totalMinutes));
const days = Math.floor(left / MINUTES_IN_DAY);
left -= days * MINUTES_IN_DAY;
const hours = Math.floor(left / 60);
const minutes = left - hours * 60;
const out = [];
if (days) out.push(days + 'd');
if (hours) out.push(hours + 'h');
if (minutes) out.push(minutes + 'm');
return out;
}
const full = (totalMinutes) => (totalMinutes < 0 ? '-' : '') + (parts(totalMinutes).join(' ') || '0m');
// The same thing, cut to the two units that matter to a reader.
const brief = (totalMinutes) =>
(totalMinutes < 0 ? '-' : '') + (parts(totalMinutes).slice(0, 2).join(' ') || '0m');
for (const m of [0, 45, 60, 135, 1440, 1500, 1501, 1441]) {
console.log(String(m).padStart(5), 'minutes ->', brief(m).padEnd(8), '(full: ' + full(m) + ')');
}
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('nothing is still worth printing', brief(0), '0m');
test('under an hour is minutes alone', brief(45), '45m');
test('a whole hour drops the empty minutes', brief(60), '1h');
test('the usual case', brief(135), '2h 15m');
test('a whole day, then a day and an hour', [brief(1440), brief(1500)], ['1d', '1d 1h']);
test('the third unit is dropped, and that is the point', [brief(1501), full(1501)], ['1d 1h', '1d 1h 1m']);
test('a zero in the middle lets minutes into the second slot', brief(1441), '1d 1m');
test('a negative duration keeps its sign', brief(-90), '-1h 30m');
test('and a fractional minute is truncated, not rounded', [brief(90.9), full(-0.5)], ['1h 30m', '-0m']);
1d 1h 1m 1s is precise and unreadable. Cutting to the two largest non-zero units is what makes a duration scannable, and the sixth assertion shows what is being thrown away deliberately. Note that the units dropped are the smallest ones, so the error is always small relative to the number shown — cutting the largest units instead would be a catastrophe.
The zero-unit case is the interesting one. Because parts are collected only when non-zero, 1441 minutes comes out as 1d 1m rather than 1d 0h, which is what a fixed days + 'd ' + hours + 'h' template would print. Whether you want that or a padded 1d 0h 1m is a product decision; the array-then-slice shape makes either one a one-line change.
-0m from full(-0.5) is the loose end. The sign is taken from the input while the digits come from the truncated absolute value, so a duration that rounds away to nothing keeps a minus it has not earned. If durations can arrive fractional, decide at the boundary whether to round or truncate, and do it before the formatter sees the number.
Common mistakes
- Using a fixed template like
days + 'd ' + hours + 'h'. It prints0d 2hand1d 0h. Collect only the parts that aren't zero. - Starting from the smallest unit. Work from days down, or the remainders don't add up.
- Letting
Math.floorsee a negative number. Take the sign off first and add it back at the end.
Try it yourself
- Add seconds: write
briefSeconds(total)that gives labels like2m 5sand1h 1m. - Make the number of units a parameter, so
brief(1501, 3)gives1d 1h 1m. - Write a long version that says
2 hours 15 minutes, using "hour" for 1.