2021-12-22 22:08:28 +03:00
|
|
|
import { format, formatISO, isBefore, isEqual, isWithinInterval, parse, parseISO as stdParseISO } from 'date-fns';
|
2023-02-18 12:40:37 +03:00
|
|
|
import type { OptionalString } from '../utils';
|
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
|
|
|
|
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);
|
|
|
|
};
|
|
|
|
|
2022-10-23 11:43:01 +03:00
|
|
|
export const formatDate = (theFormat = STANDARD_DATE_FORMAT) => (date?: NullableDate) => formatDateFromFormat(
|
|
|
|
date,
|
|
|
|
theFormat,
|
|
|
|
);
|
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
|
|
|
|
2022-12-18 15:17:49 +03:00
|
|
|
export const formatHumanFriendly = formatDate(STANDARD_DATE_AND_TIME_FORMAT);
|
|
|
|
|
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
|
|
|
|
2022-11-26 11:11:46 +03:00
|
|
|
export const dateOrNull = (date?: string): Date | null => (date ? parseISO(date) : null);
|
|
|
|
|
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);
|