Skip to content

Commit

Permalink
fix: createDateFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
djalmajr committed Apr 23, 2023
1 parent 46f0d81 commit 77e612e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/formatDate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { curry } from './curry';
import { parseDate } from './parseDate';

export const createDateFormatter = curry((locale: string, date: Date | string) => {
return date ? new Intl.DateTimeFormat(locale).format(new Date(date)) : null;
export const createDateFormatter = curry((locale: string, value: Date | string) => {
const date = parseDate(value);
return date ? new Intl.DateTimeFormat(locale).format(date) : value;
});

export const formatBRDate = createDateFormatter('pt-BR');
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export * from './not';
export * from './obj2arr';
export * from './omit';
export * from './parseCurrency';
export * from './parseDate';
export * from './parseJSON';
export * from './parseJWT';
export * from './pascalCase';
Expand Down
17 changes: 17 additions & 0 deletions src/parseDate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { isString } from './isString';

export function parseDate(date?: unknown) {
if (date instanceof Date) return date;
if (isString(date)) {
let arr;
const rx1 = /^(\d{4})-(\d{2})-(\d{2})/;
const rx2 = /^(\d{2})\/(\d{2})\/(\d{4})/;
const getDate = ([y, m, d]: string[]) => {
const val = new Date(~~y, ~~m - 1, ~~d, 0, 0, 0);
return ~~m <= 12 && val.getTime() ? val : null;
};
if ((arr = date.match(rx1))) return getDate(arr.slice(1, 4));
if ((arr = date.match(rx2))) return getDate(arr.slice(1, 4).reverse());
}
return null;
}

0 comments on commit 77e612e

Please sign in to comment.