2021-12-22 22:08:28 +03:00
|
|
|
import { format, formatISO, isBefore, isEqual, isWithinInterval, parse, parseISO as stdParseISO } from 'date-fns';
|
2020-08-22 10:48:55 +03:00
|
|
|
|
2022-10-23 11:43:01 +03:00
|
|
|
export const STANDARD_DATE_FORMAT = 'yyyy-MM-dd';
|
|
|
|
|
|
|
|
export const STANDARD_DATE_AND_TIME_FORMAT = 'yyyy-MM-dd HH:mm';
|
|
|
|
|
2021-12-22 22:08:28 +03:00
|
|
|
export type DateOrString = Date | string;
|
|
|
|
|
2021-06-24 21:13:06 +03:00
|
|
|
type NullableDate = DateOrString | null;
|
2020-08-22 10:48:55 +03:00
|
|
|
|
2022-12-05 19:18:00 +03:00
|
|
|
export const now = () => new Date();
|
|
|
|
|
2021-06-24 21:13:06 +03:00
|
|
|
export const isDateObject = (date: DateOrString): date is Date => typeof date !== 'string';
|
2020-08-22 10:48:55 +03:00
|
|
|
|
2023-07-31 21:24:04 +03:00
|
|
|
const formatDateFromFormat = (date?: NullableDate, theFormat?: string): string | null | undefined => {
|
2021-06-24 21:13:06 +03:00
|
|
|
if (!date || !isDateObject(date)) {
|
|
|
|
return date;
|
|
|
|
}
|
2020-08-22 10:48:55 +03:00
|
|
|
|
2021-06-24 21:13:06 +03:00
|
|
|
return theFormat ? format(date, theFormat) : formatISO(date);
|
|
|
|
};
|
|
|
|
|
2020-08-22 19:32:48 +03:00
|
|
|
export const formatIsoDate = (date?: NullableDate) => formatDateFromFormat(date, undefined);
|
2020-12-15 00:58:15 +03:00
|
|
|
|
2023-07-31 19:10:34 +03:00
|
|
|
export const formatInternational = (date?: NullableDate) => formatDateFromFormat(date, STANDARD_DATE_FORMAT);
|
2021-06-25 20:52:50 +03:00
|
|
|
|
2023-07-31 19:10:34 +03:00
|
|
|
export const formatHumanFriendly = (date?: NullableDate) => formatDateFromFormat(date, STANDARD_DATE_AND_TIME_FORMAT);
|
2022-12-18 15:17:49 +03:00
|
|
|
|
2022-12-05 19:18:00 +03:00
|
|
|
export const parseDate = (date: string, theFormat: string) => parse(date, theFormat, now());
|
2021-10-24 11:31:32 +03:00
|
|
|
|
2022-03-26 14:17:42 +03:00
|
|
|
export const parseISO = (date: DateOrString): Date => (isDateObject(date) ? date : stdParseISO(date));
|
2021-10-24 11:31:32 +03:00
|
|
|
|
|
|
|
export const isBetween = (date: DateOrString, start?: DateOrString, end?: DateOrString): boolean => {
|
2021-12-22 22:08:28 +03:00
|
|
|
try {
|
|
|
|
return isWithinInterval(parseISO(date), { start: parseISO(start ?? date), end: parseISO(end ?? date) });
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
2021-10-24 11:31:32 +03:00
|
|
|
}
|
|
|
|
};
|
2021-12-22 22:08:28 +03:00
|
|
|
|
|
|
|
export const isBeforeOrEqual = (date: Date | number, dateToCompare: Date | number) =>
|
|
|
|
isEqual(date, dateToCompare) || isBefore(date, dateToCompare);
|