You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.7KB

  1. import { format, isValid, parse, parseISO } from "date-fns";
  2. export const DEFAULT_DATE_FORMAT = "yyyy/MM/dd";
  3. export const DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss";
  4. export const DEFAULT_DATE_TIME_FORMAT_ANOTHER1 = "yyyy-MM-dd HH:mm:ss";
  5. export const DEFAULT_YYYYMM_FORMAT = "yyyyMM";
  6. type Input = Date | string | null | undefined;
  7. export const formatDateStr = (source: Input) => {
  8. return formatToStr(source, DEFAULT_DATE_FORMAT);
  9. };
  10. export const formatDateTimeStr = (source: Date | string | null | undefined) => {
  11. return formatToStr(source, DEFAULT_DATE_TIME_FORMAT);
  12. };
  13. export const formatYYYYMMStr = (source: Date | string | null | undefined) => {
  14. return formatToStr(source, DEFAULT_YYYYMM_FORMAT);
  15. };
  16. const formatToStr = (source: Input, formatStr: string) => {
  17. if (source === null || source === undefined) return "";
  18. if (source instanceof Date) return format(source, formatStr);
  19. return format(parseISO(source), formatStr);
  20. };
  21. export const now = () => {
  22. return new Date();
  23. };
  24. export const nowStr = (): string => {
  25. return formatDateTimeStr(now());
  26. };
  27. export const dateParse = (source: Input): Date | null => {
  28. return parseFromFormat(source, DEFAULT_DATE_FORMAT);
  29. };
  30. export const dateTimeParse = (source: Input): Date | null => {
  31. return (
  32. parseFromFormat(source, DEFAULT_DATE_TIME_FORMAT) ??
  33. parseFromFormat(source, DEFAULT_DATE_TIME_FORMAT_ANOTHER1)
  34. );
  35. };
  36. const parseFromFormat = (source: Input, format: string): Date | null => {
  37. if (source === null || source === undefined) return null;
  38. if (source instanceof Date) return source;
  39. const ret = parse(source, format, new Date());
  40. if (isValid(ret)) {
  41. return ret;
  42. }
  43. return null;
  44. };