Skip to content

Commit

Permalink
[v15] Web: intl add a date time short formatter (#39965)
Browse files Browse the repository at this point in the history
* Web: intl add a date time short formatter

* Address CRs
  • Loading branch information
kimlisa authored Mar 28, 2024
1 parent 644d7bc commit 6077fd7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion web/packages/shared/services/loc/loc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { displayDate, displayDateTime } from './loc';
import { displayDate, displayDateTime, dateTimeShortFormat } from './loc';

const testDate = new Date('2022-01-28T16:00:44.309Z');

Expand All @@ -31,3 +31,7 @@ test('displayDateTime', () => {

expect(output).toBe('2022-01-28 16:00:44');
});

test('dateTimeShortFormat', () => {
expect(dateTimeShortFormat(testDate)).toEqual('4:00 PM');
});
13 changes: 13 additions & 0 deletions web/packages/shared/services/loc/loc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
}

0 comments on commit 6077fd7

Please sign in to comment.