Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v15] Web: intl add a date time short formatter #39965

Merged
merged 2 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
Loading