3 differenceInMilliseconds,
14 import { DAY } from '../constants';
16 interface FormatOptions {
20 export const YEAR_REGEX = /[0-9]{4}/i;
23 * Get a list with the names of the days of the week according to current locale, where Sunday is the start of the week.
25 export const getFormattedWeekdays = (stringFormat: string, options?: FormatOptions) => {
26 const zeroTime = new Date(0);
27 const weekdays = eachDayOfInterval({ start: startOfWeek(zeroTime), end: endOfWeek(zeroTime) });
29 return weekdays.map((day) => format(day, stringFormat, options));
33 * Get a list with the names of the days of the week according to current locale
35 export const getFormattedMonths = (stringFormat: string, options?: FormatOptions) => {
36 const dummyDate = startOfYear(new Date(0));
37 const dummyMonths = Array.from({ length: 12 }).map((_, i) => addMonths(dummyDate, i));
39 return dummyMonths.map((date) => format(date, stringFormat, options));
43 * Get the index of the start of week day for a given date-fn locale
45 export const getWeekStartsOn = (locale?: Locale) => {
46 return locale?.options?.weekStartsOn || 0;
49 export const getTimeRemaining = (earlierDate: Date, laterDate: Date) => {
57 firstDateWasLater: false,
60 if (earlierDate === laterDate) {
66 if (isAfter(earlierDate, laterDate)) {
69 result.firstDateWasLater = true;
71 earlier = earlierDate;
75 result.years = later.getFullYear() - earlier.getFullYear();
76 result.months = later.getMonth() - earlier.getMonth();
77 result.days = later.getDate() - earlier.getDate();
78 result.hours = later.getHours() - earlier.getHours();
79 result.minutes = later.getMinutes() - earlier.getMinutes();
80 result.seconds = later.getSeconds() - earlier.getSeconds();
82 if (result.seconds < 0) {
87 if (result.minutes < 0) {
92 if (result.hours < 0) {
97 if (result.days < 0) {
98 const daysInLastFullMonth = getDaysInMonth(
99 sub(new Date(`${later.getFullYear()}-${later.getMonth() + 1}`), { months: 1 })
101 if (daysInLastFullMonth < earlier.getDate()) {
103 result.days += daysInLastFullMonth + (earlier.getDate() - daysInLastFullMonth);
105 result.days += daysInLastFullMonth;
110 if (result.months < 0) {
118 export const getDifferenceInDays = (earlierDate: Date, laterDate: Date) => {
119 const diff = differenceInMilliseconds(laterDate, earlierDate);
120 return Math.floor(diff / DAY);
123 export const isValidDate = (date: Date) => {
124 return date instanceof Date && !Number.isNaN(date.getTime());