diff --git a/web/packages/shared/services/loc/loc.test.ts b/web/packages/shared/services/loc/loc.test.ts index 46b8d5608d52e..b66e546ae5abb 100644 --- a/web/packages/shared/services/loc/loc.test.ts +++ b/web/packages/shared/services/loc/loc.test.ts @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import { displayDate, displayDateTime } from './loc'; +import { displayDate, displayDateTime, dateTimeShortFormat } from './loc'; const testDate = new Date('2022-01-28T16:00:44.309Z'); @@ -31,3 +31,7 @@ test('displayDateTime', () => { expect(output).toBe('2022-01-28 16:00:44'); }); + +test('dateTimeShortFormat', () => { + expect(dateTimeShortFormat(testDate)).toEqual('4:00 PM'); +}); diff --git a/web/packages/shared/services/loc/loc.ts b/web/packages/shared/services/loc/loc.ts index e4af2b6663f13..dc33c09b5cf2a 100644 --- a/web/packages/shared/services/loc/loc.ts +++ b/web/packages/shared/services/loc/loc.ts @@ -21,6 +21,7 @@ import { format } from 'date-fns'; import Logger from 'shared/libs/logger'; import cfg from 'shared/config'; +const DEFAULT_LOCALE = 'en-US'; const isTest = process.env.NODE_ENV === 'test'; const logger = Logger.create('services/loc'); @@ -83,3 +84,15 @@ export function displayDateTime(date: Date) { export function dateToUtc(date: Date) { return new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000); } + +/** + * Accepts a date and returns the formatted time part of the date. + * The format depends on the browser and system settings locale, + * eg: if locale was `en-US` the returned value will be say `4:00 PM`. + * + * During tests, the locale will always default to `en-US`. + */ +export function dateTimeShortFormat(date: Date) { + const locale = isTest ? DEFAULT_LOCALE : undefined; + return new Intl.DateTimeFormat(locale, { timeStyle: 'short' }).format(date); +}