From: Tim Wood Date: Mon, 20 May 2013 16:31:26 +0000 (-0700) Subject: Using first valid format when parsing multiple formats - #653 #788 X-Git-Tag: 2.1.0~36 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=10b413e53abd7700561d9e471d61e1da072b4355;p=thirdparty%2Fmoment.git Using first valid format when parsing multiple formats - #653 #788 --- diff --git a/moment.js b/moment.js index cf1cee9db..09d0d5596 100644 --- a/moment.js +++ b/moment.js @@ -857,17 +857,12 @@ i, currentScore; - for (i = config._f.length; i > 0; i--) { + for (i = 0; i < config._f.length; i++) { tempConfig = extend({}, config); - tempConfig._f = config._f[i - 1]; + tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); tempMoment = new Moment(tempConfig); - if (tempMoment.isValid()) { - bestMoment = tempMoment; - break; - } - currentScore = compareArrays(tempConfig._a, tempMoment.toArray()); if (currentScore < scoreToBeat) { diff --git a/test/moment/create.js b/test/moment/create.js index 96d058fad..a82c4e63b 100644 --- a/test/moment/create.js +++ b/test/moment/create.js @@ -234,10 +234,17 @@ exports.create = { }, "string with array of formats" : function(test) { - test.expect(3); - test.equal(moment('11-02-1999', ['MM-DD-YYYY', 'DD-MM-YYYY']).format('MM DD YYYY'), '02 11 1999', 'switching month and day'); + test.expect(6); + + test.equal(moment('11-02-1999', ['MM-DD-YYYY', 'DD-MM-YYYY']).format('MM DD YYYY'), '11 02 1999', 'switching month and day'); test.equal(moment('02-11-1999', ['MM/DD/YYYY', 'YYYY-MM-DD', 'MM-DD-YYYY']).format('MM DD YYYY'), '02 11 1999', 'year last'); test.equal(moment('1999-02-11', ['MM/DD/YYYY', 'YYYY-MM-DD', 'MM-DD-YYYY']).format('MM DD YYYY'), '02 11 1999', 'year first'); + + test.equal(moment('02-11-1999', ['MM/DD/YYYY', 'YYYY-MM-DD']).format('MM DD YYYY'), '02 11 1999', 'year last'); + test.equal(moment('1999-02-11', ['MM/DD/YYYY', 'YYYY-MM-DD']).format('MM DD YYYY'), '02 11 1999', 'year first'); + + test.equal(moment('01', ["MM", "DD"])._f, "MM", "Should use first valid format"); + test.done(); }, diff --git a/test/moment/format.js b/test/moment/format.js index b91c61378..6e84ba355 100644 --- a/test/moment/format.js +++ b/test/moment/format.js @@ -56,7 +56,7 @@ exports.format = { "format multiple with zone" : function(test) { test.expect(1); - var b = moment('2012-10-08 -1200', ['YYYY ZZ', 'YYYY-MM-DD ZZ']); + var b = moment('2012-10-08 -1200', ['YYYY-MM-DD HH:mm ZZ', 'YYYY-MM-DD ZZ', 'YYYY-MM-DD']); test.equals(b.format('YYYY-MM'), '2012-10', 'Parsing multiple formats should not crash with different sized formats'); test.done(); },