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

34 lines
880 B
JavaScript
Raw Normal View History

2023-12-24 17:49:23 +03:00
import mem from './mem';
const { locale } = new Intl.DateTimeFormat().resolvedOptions();
2023-12-24 17:49:23 +03:00
const _DateTimeFormat = (opts) => {
const { dateYear, hideTime, formatOpts } = opts || {};
2023-03-01 15:07:22 +03:00
const currentYear = new Date().getFullYear();
2023-12-24 17:49:23 +03:00
return Intl.DateTimeFormat(locale, {
2023-03-01 15:07:22 +03:00
// Show year if not current year
2023-12-24 17:49:23 +03:00
year: dateYear === currentYear ? undefined : 'numeric',
2023-03-01 15:07:22 +03:00
month: 'short',
day: 'numeric',
// Hide time if requested
hour: hideTime ? undefined : 'numeric',
minute: hideTime ? undefined : 'numeric',
...formatOpts,
2023-12-24 17:49:23 +03:00
});
};
const DateTimeFormat = mem(_DateTimeFormat);
function niceDateTime(date, dtfOpts) {
if (!(date instanceof Date)) {
date = new Date(date);
}
const DTF = DateTimeFormat({
dateYear: date.getFullYear(),
...dtfOpts,
});
const dateText = DTF.format(date);
2023-03-01 15:07:22 +03:00
return dateText;
}
export default niceDateTime;