From db8a377b2f48ca5ff3d7be68bd9f7c12233a0fcf Mon Sep 17 00:00:00 2001 From: Sergei Zharinov Date: Thu, 6 Apr 2023 10:17:57 +0300 Subject: [PATCH] feat(util/pretty-time): Ensure support for `years`, `months` and `weeks` (#21366) --- lib/util/pretty-time.spec.ts | 8 ++++++++ lib/util/pretty-time.ts | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/util/pretty-time.spec.ts b/lib/util/pretty-time.spec.ts index dff57198a07736..a9f291e467a9c6 100644 --- a/lib/util/pretty-time.spec.ts +++ b/lib/util/pretty-time.spec.ts @@ -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} diff --git a/lib/util/pretty-time.ts b/lib/util/pretty-time.ts index 63d88a598c71ad..c34e9098119338 100644 --- a/lib/util/pretty-time.ts +++ b/lib/util/pretty-time.ts @@ -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;