📅  最后修改于: 2023-12-03 15:30:50.843000             🧑  作者: Mango
formatDuration
is a Javascript function that can be used to format time duration into a human-readable string. This function takes an input duration in seconds and returns a string that represents the same duration in terms of years, months, days, hours, minutes and seconds.
The formatDuration
function takes in a single argument, which is the duration in seconds. The output from the function is a string that represents the input duration in a human-readable format.
Here's an example of how to use the formatDuration
function:
const durationInSeconds = 123456;
const formattedDuration = formatDuration(durationInSeconds);
console.log(formattedDuration); // Output: 1 day, 10 hours, 17 minutes, and 36 seconds
The formatDuration
function first initializes an empty array to store the different time units that make up the input duration. The function then computes the number of years, months, days, hours, minutes and seconds that make up the input duration by dividing the input duration by the appropriate number of seconds in each time unit.
For example, to calculate the number of days in the input duration, we can divide the input duration by the number of seconds in a day (which is 24 * 60 * 60 = 86400). The remainder of this division is then used to calculate the remaining time units. Finally, the function constructs a human-readable string by concatenating the various time units and their corresponding values.
Here's the source code for the formatDuration
function:
function formatDuration(durationInSeconds) {
const units = [
{label: 'year', value: 365 * 24 * 60 * 60},
{label: 'month', value: 30 * 24 * 60 * 60},
{label: 'day', value: 24 * 60 * 60},
{label: 'hour', value: 60 * 60},
{label: 'minute', value: 60},
{label: 'second', value: 1},
];
const parts = [];
units.forEach(({label, value}) => {
if (durationInSeconds >= value) {
const numUnits = Math.floor(durationInSeconds / value);
durationInSeconds -= numUnits * value;
parts.push(`${numUnits} ${label}${numUnits > 1 ? 's' : ''}`);
}
});
const lastPart = parts.pop();
if (parts.length) {
return `${parts.join(', ')}, and ${lastPart}`;
} else {
return lastPart;
}
}
Here are some examples of how the formatDuration
function can be used:
formatDuration(0)
returns "0 seconds"
formatDuration(60)
returns "1 minute"
formatDuration(3600)
returns "1 hour"
formatDuration(86400)
returns "1 day"
formatDuration(123456)
returns "1 day, 10 hours, 17 minutes, and 36 seconds"
formatDuration(3600 * 24 * 365)
returns "1 year"
formatDuration(3600 * 24 * 365 * 2)
returns "2 years"
formatDuration(3600 * 24 * 365 * 2 + 3600 * 24 * 30 * 4)
returns "2 years, 4 months, and 1 day"
The formatDuration
function is a simple but handy utility to have when working with time durations in a Javascript project. By using this function, you can easily format a duration into a human-readable string that makes it easy for users to understand and work with.