From: Iskren Chernev Date: Wed, 11 Dec 2013 18:29:53 +0000 (-0800) Subject: Fix iso week parsing for small years X-Git-Tag: 2.5.0^2~9^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=80680ee0992383be1b50d41a259863f2154f777b;p=thirdparty%2Fmoment.git Fix iso week parsing for small years Apparently Date.UTC works only for years after 1900: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date To form an iso date, from any given year you should use an iso formatted string. That string doesn't need 'Z' in the end ... --- diff --git a/moment.js b/moment.js index 63a6d32b4..a22e7e329 100644 --- a/moment.js +++ b/moment.js @@ -361,14 +361,14 @@ // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison - function leftZeroFill(number, targetLength) { + function leftZeroFill(number, targetLength, forceSign) { var output = Math.abs(number) + '', sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } - return (sign ? '' : '-') + output; + return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime @@ -1115,8 +1115,9 @@ //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { fixYear = function (val) { + var int_val = parseInt(val, 10); return val ? - (val.length < 3 ? (parseInt(val, 10) > 68 ? '19' + val : '20' + val) : val) : + (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) : (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]); }; @@ -1481,7 +1482,10 @@ //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { - var d = new Date(Date.UTC(year, 0)).getUTCDay(), + // The only solid way to create an iso date from year is to use + // a string format (Date.UTC handles only years > 1900). Don't ask why + // it doesn't need Z at the end. + var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(), daysToAdd, dayOfYear; weekday = weekday != null ? weekday : firstDayOfWeek; diff --git a/test/moment/create.js b/test/moment/create.js index 6c3f38449..a5dac42bb 100644 --- a/test/moment/create.js +++ b/test/moment/create.js @@ -733,6 +733,9 @@ exports.create = { //can parse other stuff too test.equal(moment('1999-W37-4 3:30', 'GGGG-[W]WW-E HH:mm').format('YYYY MM DD HH:mm'), '1999 09 16 03:30', "parsing weeks and hours"); + // Years less than 100 + ver('0098-06', 'GGGG-WW', "0098 02 03", "small years work", true); + test.done(); },