parser.ts 862 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * @file
  3. * Various date-related analysis methods
  4. */
  5. import { isValid, parseISO, parse, Locale } from 'date-fns';
  6. /**
  7. * Parsing value to Date object
  8. */
  9. export function compatiableParse(
  10. value: string,
  11. formatToken?: string,
  12. baseDate?: Date,
  13. locale?: Locale
  14. ): Date | null {
  15. let result = null;
  16. if (value) {
  17. if (formatToken) {
  18. baseDate = baseDate || new Date();
  19. result = parse(value, formatToken, baseDate, { locale });
  20. }
  21. if (!isValid(result)) {
  22. result = parseISO(value);
  23. }
  24. if (!isValid(result)) {
  25. result = new Date(Date.parse(value));
  26. }
  27. const yearInvalid = isValid(result) && String(result.getFullYear()).length > 4;
  28. if (!isValid(result) || yearInvalid) {
  29. result = null;
  30. }
  31. }
  32. return result;
  33. }