Skip to content

Instantly share code, notes, and snippets.

@krutoo
Last active January 26, 2022 19:31
Show Gist options
  • Save krutoo/c88dc9259e0ff531f3a640d5c3c6f267 to your computer and use it in GitHub Desktop.
Save krutoo/c88dc9259e0ff531f3a640d5c3c6f267 to your computer and use it in GitHub Desktop.
date-fns parse multiple formats
import { default as parse } from 'date-fns/parse';
import { default as isValid } from 'date-fns/isValid';
// like parse but second argument must array of strings
// returns date
export const parseMultiple = (
dateString,
formatString,
referenceDate,
options
) => {
let result;
if (Array.isArray(formatString)) {
for (let i = 0; i < formatString.length; i++) {
result = parse(dateString, formatString[i], referenceDate, options);
if (isValid(result)) { break; }
}
} else {
result = parse(dateString, formatString, referenceDate, options);
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment