EvanHahn / HumanizeDuration.js

361000 becomes "6 minutes, 1 second"

Home Page:https://evanhahn.github.io/HumanizeDuration.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow to not skip zeros

hovancik opened this issue · comments

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

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.