Skip to content

Commit

Permalink
feat(util/pretty-time): Ensure support for years, months and `wee…
Browse files Browse the repository at this point in the history
…ks` (#21366)
  • Loading branch information
zharinov authored Apr 6, 2023
1 parent cec928d commit db8a377
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 8 additions & 0 deletions lib/util/pretty-time.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ describe('util/pretty-time', () => {
${'1hour 1 min 1s'} | ${1 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1000}
${'1h 1m 1s 1ms'} | ${1 * 60 * 60 * 1000 + 1 * 60 * 1000 + 1000 + 1}
${'3 days'} | ${3 * 24 * 60 * 60 * 1000}
${'1 week'} | ${7 * 24 * 60 * 60 * 1000}
${'1 month'} | ${30 * 24 * 60 * 60 * 1000}
${'1 M'} | ${30 * 24 * 60 * 60 * 1000}
${'2 months'} | ${2 * 30 * 24 * 60 * 60 * 1000}
${'1month'} | ${30 * 24 * 60 * 60 * 1000}
${'1M'} | ${30 * 24 * 60 * 60 * 1000}
${'2months'} | ${2 * 30 * 24 * 60 * 60 * 1000}
${'1 year'} | ${365.25 * 24 * 60 * 60 * 1000}
${'0'.repeat(100)} | ${0}
${'0'.repeat(101)} | ${null}
${'1 whatever'} | ${null}
Expand Down
8 changes: 6 additions & 2 deletions lib/util/pretty-time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,19 @@ const splitRegex = regEx(/(.*?[a-z]+)/);

function split(time: string): string[] {
return time
.toLocaleLowerCase()
.split(splitRegex)
.map((x) => x.trim())
.filter(is.nonEmptyString);
}

function applyCustomFormat(spec: string): string {
const monthRegex = regEx(/^(\d+)\s*(?:months?|M)$/);
return spec.replace(monthRegex, (_, months) => `${months * 30} days`);
}

export function toMs(time: string): number | null {
try {
const specs = split(time);
const specs = split(time).map(applyCustomFormat);
if (!specs.length) {
logger.debug({ time }, `Invalid time specifier: '${time}'`);
return null;
Expand Down

0 comments on commit db8a377

Please sign in to comment.