Last active
January 26, 2022 19:31
-
-
Save krutoo/c88dc9259e0ff531f3a640d5c3c6f267 to your computer and use it in GitHub Desktop.
date-fns parse multiple formats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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