mattermost-mobile/app/components/formatted_date/index.tsx
Nicolas Le Cam 0c587ab427
feat: Switch FormattedDate component to Intl.DateTimeFormat (#8276)
* feat: Switch FormattedDate component to Intl.DateTimeFormat

* feat: Revert stylistic only changes

* Add tests

* Take code review into account

* Fix tests by forcing timezone

* Use constant formats in DateSeparator to avoid uneeded rerenders

* Add UserTimezone tests
2024-10-30 14:30:17 -06:00

41 lines
1.1 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React from 'react';
import {useIntl} from 'react-intl';
import {Text, type TextProps} from 'react-native';
export type FormattedDateFormat = Exclude<Intl.DateTimeFormatOptions, 'timeZone'>;
type FormattedDateProps = TextProps & {
format?: FormattedDateFormat;
timezone?: string | UserTimezone | null;
value: number | string | Date;
}
const DEFAULT_FORMAT: FormattedDateFormat = {dateStyle: 'medium'};
const FormattedDate = ({
format = DEFAULT_FORMAT,
timezone,
value,
...props
}: FormattedDateProps) => {
const {locale} = useIntl();
let timeZone: string | undefined;
if (timezone && typeof timezone === 'object') {
timeZone = timezone.useAutomaticTimezone ? timezone.automaticTimezone : timezone.manualTimezone;
} else {
timeZone = timezone ?? undefined;
}
const formattedDate = new Intl.DateTimeFormat(locale, {
...format,
timeZone,
}).format(new Date(value));
return <Text {...props}>{formattedDate}</Text>;
};
export default FormattedDate;