欢迎各位兄弟 发布技术文章
这里的技术是共享的
To add up to it, this also gets parsed just fine:
while I assume it to fail. It would only be parsed when pattern is Otherwise, it somewhat kills the whole purpose of passing the pattern as it doesn't follow it strictly. UPDATE: I have misread the original comment at first, it seems to outline the same exact issue. |
You both have a fair point. We didn't put much thought into that but just tried to parse as many cases as possible. Before we proceed to make |
@kossnocorp Aside from this is how E.g., simple use case: user enters I ended up using |
I was building a date picker where you could either type or select a date on a calendar view. The calendar view would update to show the month with the entered date as selected immediately when the user finished typing a date. But because of this it would already move to the year 2, then 20, then 201 etc as the user was typing. I fixed it by doing an input === format(parse(input, pattern), pattern) check. |
The inability to do strict parsing also prevents my team from using date-fns. To illustrate the use case that @VasilioRuzanni and @OCJvanDijk mentioned, take a look at the first example here. The default date is today's date in the format |
To add to the use-cases: We use parse as part of some custom validators in our angular app where dd/mm/yyyy is the only accepted format - using parse handles other parts of the validator but we've had to introduce an additional regexp test to ensure the correct format before passing through to date-fns for parsing. Not the end of the world but would be good if parse actually enforced the format being passed in |
The current hack you can do is to check whether the string is the same length as the format: import parse from 'date-fns/parse';
import isDate from 'date-fns/isDate';
import isValid from 'date-fns/isValid';
/**
* Parse a string as a Date object
* @param {string} str String to parse
* @param {string} format Format of the date (see date-fns formats)
*/
const parseDate = (str, format) => {
// This condition is necessary since date-fns doesn't strictly parse the dates
// anymore:
// https://github.com/date-fns/date-fns/issues/942
if (str.length !== format.length) {
return undefined;
}
const parsed = parse(str, format, new Date());
if (isDate(parsed) && isValid(parsed)) {
return parsed;
}
return undefined;
}; |
OCJvanDijk commented on 19 Oct 2018 •edited
Is this intended? I would expect parse('2-12-12', 'yyyy-MM-dd', new Date()) to fail as the correct format would be '0002-12-12'.