phanpy/src/utils/nice-date-time.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-08-13 09:26:23 +02:00
import { i18n } from '@lingui/core';
import localeMatch from './locale-match';
2023-12-24 15:49:23 +01:00
import mem from './mem';
2024-08-13 09:26:23 +02:00
const defaultLocale = new Intl.DateTimeFormat().resolvedOptions().locale;
2023-12-24 15:49:23 +01:00
const _DateTimeFormat = (opts) => {
2024-08-13 09:26:23 +02:00
const { locale, dateYear, hideTime, formatOpts } = opts || {};
const loc =
locale && !/pseudo/i.test(locale)
? localeMatch([locale], [defaultLocale])
: defaultLocale;
2023-03-01 13:07:22 +01:00
const currentYear = new Date().getFullYear();
2024-08-20 13:58:50 +02:00
const options = {
2023-03-01 13:07:22 +01:00
// Show year if not current year
2023-12-24 15:49:23 +01:00
year: dateYear === currentYear ? undefined : 'numeric',
2023-03-01 13:07:22 +01:00
month: 'short',
day: 'numeric',
// Hide time if requested
hour: hideTime ? undefined : 'numeric',
minute: hideTime ? undefined : 'numeric',
...formatOpts,
2024-08-20 13:58:50 +02:00
};
try {
2024-08-20 14:34:42 +02:00
return Intl.DateTimeFormat(loc, options);
2024-08-20 13:58:50 +02:00
} catch (e) {
2024-08-20 14:34:42 +02:00
return Intl.DateTimeFormat(undefined, options);
2024-08-20 13:58:50 +02:00
}
2023-12-24 15:49:23 +01:00
};
const DateTimeFormat = mem(_DateTimeFormat);
function niceDateTime(date, dtfOpts) {
if (!(date instanceof Date)) {
date = new Date(date);
}
const DTF = DateTimeFormat({
dateYear: date.getFullYear(),
2024-08-13 09:26:23 +02:00
locale: i18n.locale,
2023-12-24 15:49:23 +01:00
...dtfOpts,
});
const dateText = DTF.format(date);
2023-03-01 13:07:22 +01:00
return dateText;
}
export default niceDateTime;