EvanHahn / HumanizeDuration.js

361000 becomes "6 minutes, 1 second"
https://evanhahn.github.io/HumanizeDuration.js/
The Unlicense
1.65k stars 175 forks source link

Allow to not skip zeros #219

Closed hovancik closed 9 months ago

hovancik commented 9 months ago

Let's say we have

3 minutes 2 seconds remaining
3 minutes 1 seconds remaining
**3 minutes remaining**
2 minutes 59 seconds remaining
2 minutes 58 seconds remaining

Would be nice if following could be done:

3 minutes 2 seconds remaining
3 minutes 1 seconds remaining
3 minutes 0 seconds remaining
2 minutes 59 seconds remaining
2 minutes 58 seconds remaining
EvanHahn commented 9 months ago

HumanizeDuration.js doesn't support this feature, unfortunately. This library is also in maintenance mode so I don't intend to add new features. I'm going to close this issue as a result.

Here's a solution that might work for you, which uses the parse-ms module:

import parseMilliseconds from "parse-ms";

const UNITS = ["hours", "minutes", "seconds"];

function humanize(ms) {
  const parsed = parseMilliseconds(ms);

  const result = [];
  let hasSeenNonzeroUnit = false;
  for (const unit of UNITS) {
    const unitCount = parsed[unit];

    if (unitCount || hasSeenNonzeroUnit) {
      result.push(`${unitCount} ${unit}`);
    }

    if (unitCount) hasSeenNonzeroUnit = true;
  }

  return result.join(" ");
}

console.log(humanize(10845678));
// => 3 hours 0 minutes 45 seconds

console.log(humanize(12345));
// => 12 seconds

Also happy to mention a fork in my README if you want to maintain one.