2021-12-22 22:08:28 +03:00
|
|
|
import { format, formatISO, isBefore, isEqual, isWithinInterval, parse, parseISO as stdParseISO } from 'date-fns';
|
2020-08-26 21:03:23 +03:00
|
|
|
import { OptionalString } from '../utils';
|
2020-08-22 10:48:55 +03:00
|
|
|
|
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
|
|
|
|
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
|
|
|
|
2021-06-24 21:13:06 +03:00
|
|
|
const formatDateFromFormat = (date?: NullableDate, theFormat?: string): OptionalString => {
|
|
|
|
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);
|
|
|
|
};
|
|
|
|
|
|
|
|
export const formatDate = (format = 'yyyy-MM-dd') => (date?: NullableDate) => formatDateFromFormat(date, format);
|
2020-08-22 10:48:55 +03:00
|
|
|
|
2020-08-22 19:32:48 +03:00
|
|
|
export const formatIsoDate = (date?: NullableDate) => formatDateFromFormat(date, undefined);
|
2020-12-15 00:58:15 +03:00
|
|
|
|
|
|
|
export const formatInternational = formatDate();
|
2021-06-25 20:52:50 +03:00
|
|
|
|
|
|
|
export const parseDate = (date: string, format: string) => parse(date, format, new Date());
|
2021-10-24 11:31:32 +03:00
|
|
|
|
2021-12-22 22:08:28 +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);
|