2022-02-14 10:02:17 +00:00
|
|
|
import dayjs from 'dayjs';
|
|
|
|
import advancedFormat from 'dayjs/plugin/advancedFormat';
|
2023-12-04 11:46:24 +00:00
|
|
|
import duration from 'dayjs/plugin/duration';
|
|
|
|
import relativeTime from 'dayjs/plugin/relativeTime';
|
2022-02-14 10:02:17 +00:00
|
|
|
import timezone from 'dayjs/plugin/timezone';
|
|
|
|
import utc from 'dayjs/plugin/utc';
|
2022-05-16 19:18:48 +00:00
|
|
|
import { useI18n } from 'vue-i18n';
|
2022-02-14 10:02:17 +00:00
|
|
|
|
|
|
|
dayjs.extend(timezone);
|
|
|
|
dayjs.extend(utc);
|
|
|
|
dayjs.extend(advancedFormat);
|
2023-12-04 11:46:24 +00:00
|
|
|
dayjs.extend(relativeTime);
|
|
|
|
dayjs.extend(duration);
|
2022-02-14 10:02:17 +00:00
|
|
|
|
|
|
|
export function useDate() {
|
|
|
|
function toLocaleString(date: Date) {
|
2024-01-27 20:15:10 +00:00
|
|
|
return dayjs(date).format(useI18n().t('time.template'));
|
2022-02-14 10:02:17 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 11:46:24 +00:00
|
|
|
function timeAgo(date: Date | string | number) {
|
|
|
|
return dayjs().to(dayjs(date));
|
|
|
|
}
|
|
|
|
|
|
|
|
function prettyDuration(durationMs: number) {
|
|
|
|
return dayjs.duration(durationMs).humanize();
|
|
|
|
}
|
|
|
|
|
|
|
|
const addedLocales = ['en'];
|
|
|
|
|
|
|
|
async function setDayjsLocale(locale: string) {
|
|
|
|
if (!addedLocales.includes(locale)) {
|
2024-06-06 13:16:59 +00:00
|
|
|
const l = (await import(`~/assets/dayjsLocales/${locale}.js`)) as { default: string };
|
2023-12-04 11:46:24 +00:00
|
|
|
dayjs.locale(l.default);
|
|
|
|
} else {
|
|
|
|
dayjs.locale(locale);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function durationAsNumber(durationMs: number): string {
|
|
|
|
const dur = dayjs.duration(durationMs);
|
|
|
|
return dur.format(dur.hours() > 1 ? 'HH:mm:ss' : 'mm:ss');
|
|
|
|
}
|
|
|
|
|
2022-02-14 10:02:17 +00:00
|
|
|
return {
|
|
|
|
toLocaleString,
|
2023-12-04 11:46:24 +00:00
|
|
|
timeAgo,
|
|
|
|
prettyDuration,
|
|
|
|
setDayjsLocale,
|
|
|
|
durationAsNumber,
|
2022-02-14 10:02:17 +00:00
|
|
|
};
|
|
|
|
}
|