Technologies:
Tolerim
25 days ago
How can a number duration be converted into a format that is readable by humans?
Duration | Human Readable Format |
---|---|
24 | 24 seconds |
430 | 7 minutes and 10 seconds |
600 | 10 minutes |
3600 | 1 hour |
7477 | 2 hours, 4 minutes and 37 seconds |
Intl.DateTimeFormat
and Intl.RelativeTimeFormat
but they did not provide the expected results. Therefore, I need to find a way to display the duration in human-readable format using vanilla js.Answers(1)
Tolerim
25 days ago
Verified Answer
You can create a function in vanilla JavaScript that takes an integer duration in seconds and converts it into a human-readable format. Here's an example of how you can implement this:
function formatDuration(duration) {
let hours = Math.floor(duration / 3600);
let minutes = Math.floor((duration % 3600) / 60);
let seconds = duration % 60;
let timeUnits = [];
if (hours > 0) {
timeUnits.push(hours + (hours == 1 ? ' hour' : ' hours'));
}
if (minutes > 0) {
timeUnits.push(minutes + (minutes == 1 ? ' minute' : ' minutes'));
}
if (seconds > 0 || (duration == 0 && timeUnits.length == 0)) {
timeUnits.push(seconds + (seconds == 1 ? ' second' : ' seconds'));
}
if (timeUnits.length == 0) {
return '0 seconds';
}
if (timeUnits.length == 1) {
return timeUnits[0];
}
let lastUnit = timeUnits.pop();
return timeUnits.join(', ') + ' and ' + lastUnit;
}
The formatDuration function takes an integer duration in seconds as input and returns a human-readable format (for example, "7 minutes and 10 seconds") as output.
First, the function calculates the number of hours, minutes and seconds in the duration using division and modulo operators. Then, it creates an empty timeUnits array to store the duration units (hours, minutes, and seconds) that are greater than 0.
Next, the function checks if the duration has hours, minutes or seconds values that need to be added to the timeUnits array. If a value is found, it's added to timeUnits with a human-readable label (e.g. "1 hour" or "30 seconds").
If the duration is 0, the function returns a string "0 seconds". If there is only one duration unit, the function returns that unit. If there are more than one duration units, the function joins them with commas and adds "and" before the last unit.
Finally, you can call this function whenever you need to display a duration in a human-readable format.