jws-frontend/src/utils/datetime.ts

79 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-04-02 11:02:16 +07:00
import moment from 'moment';
2024-06-27 04:59:11 +00:00
import 'moment/dist/locale/th';
import 'moment/dist/locale/en-gb';
2024-04-02 11:02:16 +07:00
2024-06-27 04:59:11 +00:00
moment.locale('en-gb');
2024-04-02 11:02:16 +07:00
export function setLocale(locale: string) {
moment.locale(locale);
}
export function dateFormat(
date?: string | Date | null,
fullmonth = false,
time = false,
2024-06-27 04:59:11 +00:00
number = false,
2024-04-02 11:02:16 +07:00
) {
const m = moment(date);
if (!m.isValid()) return '';
2024-06-27 04:59:11 +00:00
let yearOffset = 0;
if (moment.locale() === 'th') {
yearOffset = 543;
}
if (time) return m.format('HH:mm');
if (number) {
let formattedNumberDate = m.format('L');
if (yearOffset) {
const adjustedYear = m.year() + yearOffset;
formattedNumberDate = formattedNumberDate.replace(
m.year().toString(),
adjustedYear.toString(),
);
}
return formattedNumberDate;
}
const monthFormat = fullmonth ? 'MMMM' : 'MMM';
const formattedDate = m.format(
`DD ${monthFormat} YYYY ${time ? ' HH:mm' : ''}`,
);
// Adjust year for Buddhist calendar if locale is 'th'
if (yearOffset) {
const adjustedYear = m.year() + yearOffset;
return formattedDate.replace(m.year().toString(), adjustedYear.toString());
}
return formattedDate;
}
function pad(n: number) {
return `${Math.floor(Math.abs(n))}`.padStart(2, '0');
}
function getTimezoneOffset(date: Date) {
const tzOffset = -date.getTimezoneOffset();
const diff = tzOffset >= 0 ? '+' : '-';
return diff + pad(tzOffset / 60) + ':' + pad(tzOffset % 60);
}
2024-04-02 11:02:16 +07:00
2024-06-27 04:59:11 +00:00
export function toISOStringWithTimezone(date: Date) {
return (
date.getFullYear() +
'-' +
pad(date.getMonth() + 1) +
'-' +
pad(date.getDate()) +
'T' +
pad(date.getHours()) +
':' +
pad(date.getMinutes()) +
':' +
pad(date.getSeconds()) +
getTimezoneOffset(date)
);
2024-04-02 11:02:16 +07:00
}