Skip to content

Commit

Permalink
Merge 3426f5a into d0f0dd8
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbucholz committed Apr 19, 2019
2 parents d0f0dd8 + 3426f5a commit 93f0d1b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
25 changes: 19 additions & 6 deletions src/lib/create/from-string-and-array.js
Expand Up @@ -11,7 +11,9 @@ export function configFromStringAndArray(config) {

scoreToBeat,
i,
currentScore;
currentScore,
validFormatFound,
bestFormatIsValid = false;

if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
Expand All @@ -21,15 +23,16 @@ export function configFromStringAndArray(config) {

for (i = 0; i < config._f.length; i++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);

if (!isValid(tempConfig)) {
continue;
if (isValid(tempConfig)) {
validFormatFound = true;
}

// if there is any input that was not parsed add a penalty for that format
Expand All @@ -40,9 +43,19 @@ export function configFromStringAndArray(config) {

getParsingFlags(tempConfig).score = currentScore;

if (scoreToBeat == null || currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (!bestFormatIsValid) {
if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (validFormatFound) {
bestFormatIsValid = true;
}
}
} else {
if (currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/test/moment/create.js
Expand Up @@ -422,6 +422,11 @@ test('string with array of formats + ISO', function (assert) {
assert.equal(moment('2014-05-05', ['YYYY-MM-DD', moment.ISO_8601]).parsingFlags().iso, false, 'iso: edge case array precedence not iso');
});

test('strict parsing invalid date against array of formats', function (assert) {
var b = moment('2/30/2019 7:00pm', ['M/DD/YYYY h:mma", "MM/DD/YYYY h:mma", "M-D-YYYY h:mma", "MM-D-YYYY h:mma'], true);
assert.deepEqual(b.parsingFlags().parsedDateParts, [2019,1,30,7,0], 'strict parsing multiple formats should still select the best format even if the date is invalid');
});

test('string with format - years', function (assert) {
assert.equal(moment('67', 'YY').format('YYYY'), '2067', '67 > 2067');
assert.equal(moment('68', 'YY').format('YYYY'), '2068', '68 > 2068');
Expand Down

0 comments on commit 93f0d1b

Please sign in to comment.