Skip to content

Instantly share code, notes, and snippets.

@petrvecera
Created July 31, 2021 21:35
Show Gist options
  • Save petrvecera/3daaab83c4a1efa0182ced135af717cf to your computer and use it in GitHub Desktop.
Save petrvecera/3daaab83c4a1efa0182ced135af717cf to your computer and use it in GitHub Desktop.
Fixed dateFns which doesn't include all locales
import {
getDay,
getYear,
getMonth,
getDate,
endOfMonth,
getHours,
getMinutes,
getSeconds,
addYears,
addMonths,
addDays,
setYear,
setMonth,
setDate,
setHours,
setMinutes,
setSeconds,
isAfter,
isValid,
getWeek,
startOfWeek,
format as formatDate,
parse as parseDate,
} from "date-fns";
import enGB from "date-fns/locale/en-GB";
import type { GenerateConfig } from "rc-picker/lib/generate";
const localeParse = (format: string) => {
return format
.replace(/Y/g, "y")
.replace(/D/g, "d")
.replace(/gggg/, "yyyy")
.replace(/g/g, "G")
.replace(/([Ww])o/g, "wo");
};
const generateConfig: GenerateConfig<Date> = {
// get
getNow: () => new Date(),
getFixedDate: (string) => new Date(string),
getEndDate: (date) => endOfMonth(date),
getWeekDay: (date) => getDay(date),
getYear: (date) => getYear(date),
getMonth: (date) => getMonth(date),
getDate: (date) => getDate(date),
getHour: (date) => getHours(date),
getMinute: (date) => getMinutes(date),
getSecond: (date) => getSeconds(date),
// set
addYear: (date, diff) => addYears(date, diff),
addMonth: (date, diff) => addMonths(date, diff),
addDate: (date, diff) => addDays(date, diff),
setYear: (date, year) => setYear(date, year),
setMonth: (date, month) => setMonth(date, month),
setDate: (date, num) => setDate(date, num),
setHour: (date, hour) => setHours(date, hour),
setMinute: (date, minute) => setMinutes(date, minute),
setSecond: (date, second) => setSeconds(date, second),
// Compare
isAfter: (date1, date2) => isAfter(date1, date2),
isValidate: (date) => isValid(date),
locale: {
getWeekFirstDay: (locale) => {
const clone = enGB;
return clone.options?.weekStartsOn || 1;
},
getWeekFirstDate: (locale, date) => {
return startOfWeek(date, { locale: enGB });
},
getWeek: (locale, date) => {
return getWeek(date, { locale: enGB });
},
getShortWeekDays: (locale) => {
const clone = enGB;
return Array.from({ length: 7 }).map((_, i) => clone.localize?.day(i, { width: "short" }));
},
getShortMonths: (locale) => {
const clone = enGB;
return Array.from({ length: 12 }).map((_, i) =>
clone.localize?.month(i, { width: "abbreviated" }),
);
},
format: (locale, date, format) => {
if (!isValid(date)) {
return "";
}
return formatDate(date, localeParse(format), {
locale: enGB,
});
},
parse: (locale, text, formats) => {
for (let i = 0; i < formats.length; i += 1) {
const format = localeParse(formats[i]);
const formatText = text;
const date = parseDate(formatText, format, new Date(), {
locale: enGB,
});
if (isValid(date)) {
return date;
}
}
return null;
},
},
};
export default generateConfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment